Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / F#

F# Symbolic Operator

5.00/5 (3 votes)
12 Dec 2011CPOL1 min read 8.7K  
F# symbolic operator

Let's think of writing add 1 2 in the declarative way instead of traditional way 1+2 every time. It's called as a symbolic operator. F# has not only built-in symbolic operators but also custom defined own symbolic operators. It helps the developers to write code in a cleaner and elegant way. In fact, symbolic functions are not as form of operator overloading; rather functions whose names are made out of symbols.

A symbolic operator can be made up of any sequence !@#$%^&*+-/<=>~| symbols. Here, the code defines a new function ! that computes the factorial of a given number:

F#
> let rec(!) x =
if x <= 1 then 1
else x * !(x-1);;
> !5;;
val it : int = 120

To have symbolic operators that come before their parameters are known as prefix notation. You must prefix the function with a tilde ~, exclamation point ! or question mark ? operator. In the below code, the function ~++ is prefixed with a tilde and thus to call it, you write ~++ 1 2 3 rather than 1 ~++ 2 3. This enables you to use symbolic operators that more naturally fit the style of function being defined as:

C++
> let (~++) x y z = x + y + z;;
val (~++) : int-> int-> int-> int
> ~++ 1 2 3;;
val it : int = 6

In addition to allowing you to name functions that map more closely to mathematics, symbolic operators can also be passed around to higher order functions if you simply put parentheses around the symbol.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)