F Sharp Programming/Operator Overloading

Operator overloading allows programmers to provide new behavior for the default operators in F#. In practice, programmers overload operators to provide a simplified syntax for objects which can be combined mathematically.

Using Operators
You've already used operators: Here  is example of using a mathematical addition operator.

Operator Overloading
Operators are functions with special names, enclosed in brackets. They must be defined as static class members. Here's an example on declaring  operator on complex numbers:

In FSI, we can add two complex numbers as follows:

Defining New Operators
In addition to overloading existing operators, its possible to define new operators. The names of custom operators can only be one or more of the following characters:

F# supports two types of operators: infix operators and prefix operators.

Infix operators
An infix operator takes two arguments, with the operator appearing in between both arguments (i.e. ). We can define our own infix operators using the syntax:

In addition to mathematical operators, F# has a variety of infix operators defined as part of its library, for example:

Let's say we're writing an application which performs a lot of regex matching and replacing. We can match text using Perl-style operators by defining our own operators as follows:

This program outputs the following: cat =~ dog: false cat =~ cat|dog: true monkey =~ monk*: true

Prefix Operators
Prefix operators take a single argument which appears to the right side of the operator. You've already seen how the  operator is defined for ref cells:

Let's say we're writing a number crunching application, and we wanted to define some operators that work on lists of numbers. We might define some prefix operators in fsi as follows: