examples/advanced/14_operator_overloading.cat
# Exemple 14 : Surcharge d'operateurs

print("⇒ Operateurs binaires")

struct Vec2 {
    x, y
    op +(self, rhs) => { Vec2(self.x + rhs.x, self.y + rhs.y) }
    op -(self, rhs) => { Vec2(self.x - rhs.x, self.y - rhs.y) }
    op *(self, rhs) => { Vec2(self.x * rhs, self.y * rhs) }
}

a = Vec2(1, 2)
b = Vec2(3, 4)

print("a + b =", a + b)
print("a - b =", a - b)
print("a * 3 =", a * 3)

print("\n⇒ Chainage")

c = Vec2(10, 10)
print("a + b + c =", a + b + c)

print("\n⇒ Operateurs unaires")

struct Vec3 {
    x, y, z
    op -(self) => { Vec3(-self.x, -self.y, -self.z) }
}

v = Vec3(1, -2, 3)
print("v =", v)
print("-v =", -v)

print("\n⇒ Puissance et modulo")

struct Num {
    v
    op **(self, rhs) => { Num(self.v ** rhs) }
    op %(self, rhs) => { Num(self.v % rhs) }
}

n = Num(5)
print("Num(5) ** 3 =", (n ** 3).v)
print("Num(5) % 3 =", (n % 3).v)

print("\n⇒ Comparaisons")

struct Money {
    amount
    op <(self, rhs) => { self.amount < rhs.amount }
    op ==(self, rhs) => { self.amount == rhs.amount }
}

print("Money(50) < Money(100) =", Money(50) < Money(100))
print("Money(42) == Money(42) =", Money(42) == Money(42))

print("\n⇒ Heritage d'operateurs")

struct Base2D {
    x, y
    op +(self, rhs) => { Base2D(self.x + rhs.x, self.y + rhs.y) }
}

struct Velocity extends(Base2D) { }

v1 = Velocity(1, 2)
v2 = Velocity(3, 4)
print("Velocity(1,2) + Velocity(3,4) =", v1 + v2)

print("\n⇒ Reverse operators (scalaire a gauche)")

struct Wrapper {
    val
    op +(self, rhs) => { Wrapper(self.val + rhs) }
    op *(self, rhs) => { Wrapper(self.val * rhs) }
}

w = Wrapper(10)
print("w + 5 =", (w + 5).val)
print("5 + w =", (5 + w).val)
print("3 * w =", (3 * w).val)

print("\n⇒ Les builtins ne sont pas affectes")
print("1 + 2 =", 1 + 2)
print("'a' + 'b' =", "a" + "b")