F# Tutorial on F# Operator Overloading

you can redefine or overload most of the built-in operators available in f#. thus a programmer can use operators with user-defined types as well.

operators are functions with special names, enclosed in brackets. they must be defined as static class members. like any other function, an overloaded operator has a return type and a parameter list.

the following example, shows a + operator on complex numbers −

//overloading + operator
static member (+) (a : complex, b: complex) =
complex(a.x + b.x, a.y + b.y)

the above function implements the addition operator (+) for a user-defined class complex. it adds the attributes of two objects and returns the resultant complex object.

implementation of operator overloading

the following program shows the complete implementation −

//implementing a complex class with +, and - operators
//overloaded
type complex(x: float, y : float) =
   member this.x = x
   member this.y = y
   //overloading + operator
   static member (+) (a : complex, b: complex) =
      complex(a.x + b.x, a.y + b.y)

   //overloading - operator
   static member (-) (a : complex, b: complex) =
      complex(a.x - b.x, a.y - b.y)

   // overriding the tostring method
   override this.tostring() =
      this.x.tostring() + " " + this.y.tostring()

//creating two complex numbers
let c1 = complex(7.0, 5.0)
let c2 = complex(4.2, 3.1)

// addition and subtraction using the
//overloaded operators
let c3 = c1 + c2
let c4 = c1 - c2

//printing the complex numbers
printfn "%s" (c1.tostring())
printfn "%s" (c2.tostring())
printfn "%s" (c3.tostring())
printfn "%s" (c4.tostring())

when you compile and execute the program, it yields the following output −

7 5
4.2 3.1
11.2 8.1
2.8 1.9