This post is about how we can define a custom operator using F#. Defining a new operator in F# is very straightforward. For example, if one wants to define "!" as an operator to compute factorial of an integer, following is the way to do it.
Example 1: Computing factorial of an integer n
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: ! % & * + - . / < = > ? @ ^ |~ . ":" can also be used in the character sequence of symbolic operation given that it is not the first character.
Example 2: Computing <a modulo n> where a := the dividend and n := the divisor.
The following F# command utilizes the newly define modulo operator |%| to compute 23 % 3.
> 23 |%| 3;;
val it : int = 2
>
It is imperative to note that Symbolic operators adopt to use infix notation when there is more than one parameter are involved. However if the custom symbolic operator starts with following symbols : “!” “~” “?”, it works alike prefix notion. That is, operator is proceeded by its operand.
For example, if in the example 2, we have used ! as the operator of the modulo operation, we have to use it as follows : ! a n