Define symbolic operators with F#

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)
view raw sym_op.fs hosted with ❤ by GitHub

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
view raw modulo.fs hosted with ❤ by GitHub

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: