Logo

Programming-Idioms

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

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.

module vect
  private
  type, public:: vector
     real :: x,y,z
  end type vector
  public:: operator(.x.)
  interface operator(.x.)
     procedure vector_cross
  end interface operator(.x.)
contains
  function vector_cross(a,b) result(c)
    type(vector), intent(in) :: a,b
    type(vector) :: c
    c%x = a%y*b%z - a%z*b%y
    c%y = a%z*b%x - a%x*b%z
    c%z = a%x*b%y - a%y*b%x
  end function vector_cross
end module vect

You can then write a .x. b in an expression.
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