This post describes how we can define a custom operator with F#. Defining a new operator in F# is very straightforward. For instance, by using the following code, we can define “!” as an operator to compute factorial of an integer.

let rec (!) n = | |

match n with | |

| 1 -> (1) | |

| n -> n*(n-1) |

Running the following command in the interactive F# console computes the factorial for 10.

>!10;; val it : int = 3628800>

A symbolic operator can use any sequence of the following characters: ` ! % & * + - . / ? @ ^ |~`

. Note that, “:” can also be used in the character sequence of symbolic operation if and only if, it is not the first character in the operator.

Following is an example of **modulo** operator defined using F#:

let rec (|%|) a n = | |

match a, n with | |

|_ when a < n -> a | |

|_ when a>=n -> (|%|) (a-n) n | |

//Resulting signature: val ( |%| ) : int -> int -> int |

Following outputs shows how to use it from F# interactive shell.

>23 |%| 3;; val it : int = 2>3 |%| 3;; val it : int = 0>