Logo

Programming-Idioms

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

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.

local Vector={x=0,y=0,z=0}
---@type metatable
local mt={
 __index=Vector,
}
function mt.__add(a,b)
 return Vector.new(
  a.x+b.x,
  a.y+b.y,
  a.z+b.z
 )
end
function Vector.new(x,y,z)
 return setmetatable({x=x,y=y,z=z},mt)
end
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