Operator overloading in F#

More adventures with F#…

Operator overloading is documented perfectly well in Operator Overloading (F#) but to summarize I’ve created this post…

Operators in F# can be overloaded at the class, record type or global level.

Overloading an operator on a class or record type

Let’s look at the syntax for overloading an operator on a class or record type.

Note: Reproduced from the Operator Overloading (F#) page

static member (operator-symbols) (parameter-list> =
    method-body

Overloading an operator which is globally accessible

Let’s look at the syntax for overloading an operator at a global level.

Note: Reproduced from the Operator Overloading (F#) post

let [inline] (operator-symbols) parameter-list = 
    function-body

More…

You can overload the “standard” operators but you can also create your own operators. For example FAKE creates it’s own global operator to combine two file paths using the @@ operator

The below is taken from the FAKE source code available in github

let inline (@@) path1 path2 = combinePaths path1 path2

As it’s pretty obvious, this is a global level overload of a newly created operator, the @@ which takes two parameters.

Where an operator may be used for binary or unary (infix or prefix), such as + or – (+., -., &, &&, %, and %% may also be used for infix or prefix operators) we need to prefix the operator with a tilde ~, hence to overload the + and use as a unary operator we’d write something like

let inline (~+) x = [ x ]

// in use we'd have

let v = + "hello"

Whereas using the + as a binary operator we’d write something like

let inline (+) x y = [ x, y ]

// in use we'd have

let v = "hello" + "world"

If you’re coming from C# to F# you’ll have already noticed the “funky” set of operators that F# supports. As already shown with the @@ operator sample (taken from FAKE) you can combine operators to produce all sorts of new operators, for example

let (<==>) x  y = [ x, y]