Monday, January 3, 2011

First Steps In F Sharp

F# - also known as F Sharp.

As you know, there are some OOP languages out there. You probably know VB.Net, C# and Java but I'm about to talk about relatively new one.

I would like to talk a little about F Sharp.

Similar to C Sharp and VB.Net, F# is also targeting the .Net Framework and is also Object Oriented.
The main difference in F# is not it's unique syntax but rather the new point of view and better state of mind it brings to the Object Oriented Programming.

F Sharp uses "type inference" - meaning, the programmer doesn't need to keep his mind in the needed data type parameter and can just use the word "let" (similar to "var").
The data type will be deduce by the compiler itself during compilation (F# also allows explicit data types declaration).

After this short introduction to F# (very short) I would like to start the practical section.  and this post will be all about Lists in F Sharp.

Let’s make a small experiment:
Create a List of Ints in C#
List<int> newList = new List<int>();

Add the following values to this list:
newList.Add(5);
newList.Add(2);
newList.Add(-3);
newList.Add(1);

Now please try to sort it using "Absolute Value".
You'll probably find out that if you -did- manage to do this - you've used functionality programming.

In F# it's almost the same and as easy as can be once you get the point:
[5; 2; -3; 1] |> List.sortBy(fun intElem -> abs intElem)

Let’s test our C# abilities again by mapping that List of ints (each number will be powered by 3)
Again, most of you, who succeed used LINQ or other functional programming that C #allows, this is how it's don’t in F Sharp:
[5; 2; -3; 1] |> List.map(fun x-> x * x * x)

Another test for our C# (or Java) strength will be to try and filter that list for all ints that returns 0 when divided by 2.  In F Sharp it as easy as they come:
[5; 2; -3; 1] |> List.filter(fun x -> x % 2 = 0)

These were just couple of examples about F# and it's usability.  Hopefully it will help you understand the syntax and even more important - it will help you to think in functional programming.

BTW
How can we forget the immortal first program: "Hello World!" ?
printfn "Hello World!"


Good luck,
Elad Shalom,
CTO at ITweetLive.com

4 comments:

  1. Hi, Elad!

    I’m the web editor at iMasters, one of the largest developer communities in Brazil. I´d like to talk to you about republishing your article at our site.

    Can you contact me at rina.noronha@imasters.com.br?

    Bests,
    Rina Noronha
    Journalist – web editor
    www.imasters.com.br
    redacao@imasters.com.br
    rina.noronha@imasters.com.br
    +55 27 3327-0320 / +55 27 9973-0700

    ReplyDelete