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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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#:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 >