Operator overloading in F#

F# allows us to override existing operators and even create our own. There are two types of operators, prefix and infix.

Prefix operators are those which take one operand. Infix operators take two arguments.Unlike C# both operands in an infix operator must be of the same type.

Along with overloading existing operators we can create custom operators using a single or multiple characters from the following !$%&+-,/<=>?@^|~

For example, let’s define a global operator !^ which will calculate the square root of a floating point number

let inline (!^) (a: float) = Math.Sqrt(a)

and in usage

let sqrt = !^ 36.0
printfn "Sqrt %f" sqrt

An infix operator is declared taking two arguments, so here’s an example of a value to the power n, which we’ll use the operator ++ which can be defined as

let inline (++) (x: float) (y: float) = Math.Pow(x, y)

and in usage

let a = 10.0 ++ 2.0

When declaring operators on a type (as opposed to globally) we have the following

type MyClass2(x : int) =
    member this.value = x
    static member (~+) (m : MyClass2) = 
        MyClass2(m.value + 1)
    static member (+) (m : MyClass2, v : int) = 
        MyClass2(m.value + v)

// usage 

let m = new MyClass2(1)
let n = m + 5