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
Advertisements