Logo

Programming-Idioms

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

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.

data Vector a = Vector a a a

infixl 7 ×
(×) :: Num a => Vector a -> Vector a -> Vector a
Vector x1 y1 z1 × Vector x2 y2 z2 = Vector (y1 * z2 - z1 * y2) (z1 * x2 - x1 * z2) (x1 * y2 - y1 * x2)
data Vector a = Vector a a a

infixl 7 `x`
x :: Num a => Vector a -> Vector a -> Vector a
Vector x1 y1 z1 `x` Vector x2 y2 z2 = Vector (y1 * z2 - z1 * y2) (z1 * x2 - x1 * z2) (x1 * y2 - y1 * x2)
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