Logo

Programming-Idioms

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

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.

Vector = Struct.new(:x, :y, :z) do
  def * (other)
    Vector.new(
      y*other.z - z*other.y,
      z*other.x - x*other.z,
      x*other.y - y*other.x)
  end
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