Sunday, December 11, 2011

F# Symbolic Operator

Letz think of writing add 1 2 in the declarative way in stead of traditional way 1+2 everytime. Itz 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. Herez the code defines a new function ! that computes the factorial of a given number

> 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:

> 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.

No comments:

Post a Comment