Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / F#

First Steps in F#

Rate me:
Please Sign up or sign in to vote.
2.50/5 (2 votes)
13 Jun 2011CPOL2 min read 10.3K   4   1
A little about F#.

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 a relatively new one. I would like to talk a little about F# (pronounced F Sharp).

Similar to C# and VB.NET, F# also targets the .NET Framework and is also object oriented. The main difference in F# is not its unique syntax but rather the new point of view and better state of mind it brings to Object Oriented Programming.

F# 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 deduced by the compiler 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#.

Let’s see a small example:

Create a List of ints in C#:

C#
List<int> newList = new List<int>();

Add the following values to this list:

C#
newList.Add(5);
newList.Add(2);
newList.Add(-3);
newList.Add(1);

Now try to sort it using "Absolute Value". You'll probably find out that if you -do- 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:

F#
[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 have successfully used LINQ or other functional programming that C #allows, this is how it's done in F#:

F#
[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#, it as easy as:

F#
[5; 2; -3; 1] |> List.filter(fun x -> x % 2 = 0)

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

By the way, how can we forget the immortal first program: "Hello World!"?

F#
printfn "Hello World!"

Good luck!

License

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



Comments and Discussions

 
GeneralMy vote of 1 Pin
Vladimior21-Jun-13 2:06
Vladimior21-Jun-13 2:06 

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.