Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Python

Idiom #268 User-defined operator

Define a type vector containing three floating point numbers x, y, and z. Write a user-defined operator x that calculates the cross product of two vectors a and b.

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        return

    def __mul__(self, other):
        return Vector(self.y * other.z - self.z * other.y,
                      self.z * other.x - self.x * other.z,
                      self.x * other.y - self.y * other.x)

result = a * b

Python doesn't allow operators with user-defined names
class Vector:
    def __init__(self, x, y, z):
        self.a = x, y, z
    def __getitem__(self, i):
        return self.a[i]
    def __mul__(self, b):
        a = self.a
        return {
            'x': a[1] * b[2] - a[2] * b[1],
            'y': a[2] * b[0] - a[0] * b[2],
            'z': a[0] * b[1] - a[1] * b[0]
        }
a = Vector(.1, .2, .3)
b = Vector(.4, .5, .6)
x = a * b
record Vector(double X, double Y, double Z)
{
    public static Vector operator *(Vector a, Vector b)
    {
        return new(
            a.Y*b.Z - a.Z*b.Y,
            a.Z*b.X - a.X*b.Z,
            a.X*b.Y - a.Y*b.X
        );
    }
}

C# allows operator overloading but not operators with user-defined names.

Because it is ambiguous whether the * operator between two vectors is dot product, cross product, or component-wise multiplication, each of these should be implemented as a static method instead.

Refer to the built-in 3D vector type, linked as 'Origin'

New implementation...
< >
tkoenig