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 int
s 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 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:
[5; 2; -3; 1] |> List.sortBy(fun intElem -> abs intElem)
Let’s test our C# abilities again by mapping that List
of int
s (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#:
[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 int
s that returns 0 when divided by 2. In F#, it as easy as:
[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!"?
printfn "Hello World!"
Good luck!