Click here to Skip to main content
15,890,336 members
Articles / Programming Languages / F#

F# Symbolic Operator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
12 Dec 2011CPOL1 min read 8.5K   3   1
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)


Written By
Architect
India India
Ganesan Senthilvel is a passionate IT leader with demonstrated 2 decades’ experience in architecture, design and implementing cutting edge solutions to address business opportunities of Enterprise applications. He earned Masters in Computer Science and Master in Business Administration. Now, he is pursing Doctorate program in Big Data. He is consistent technical contributor via COE, Blog, Whitepaper, Summit, Certification, etc. and also highly skilled at providing coaching and mentoring to internal teams and external institutes. Earned Microsoft Certifications like MCP, MCAD and financial domain certification.
He maintains his weekly blog at http://ganesansenthilvel.blogspot.in

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kelly Cole20-Dec-11 7:29
Kelly Cole20-Dec-11 7:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.