This is the first episode of a series meant to show how easily F# adapts to the way we think. I assume no knowledge of functional languages, but I do assume knowledge of an imperative language such as C#.

___

Suppose in your application you want to do the following:

if there is a dog whose name is jerry, print “hello”.

This is how we think, i.e. how the original thought forms in our mind. But, in order to implement this thought in ordinary imperative languages (such as C++ or C# before .NET 3), we’d have to translate it more or less like that:

for each d in dogs
   if d.name = jerry then
      print "hello"

which is not close to the original sentence. As the conditions to write become more complicated, this kind of code tends to become unreadable and unmantainable.


Let us now see how much more natural it is to express the same idea in F#, and how much closer to the original sentence the F# code is.

In order to translate this to F#, it is useful to slightly rephrase our original thought like that:

if there is a dog D whose name is jerry, then print “hello”.

This is closer to F#, but let us rephrase it again slightly:

if there exists a dog D such that D.name = jerry, then print “hello”.

now the above is practically F#. In fact, the real F# code is:

if exists dogs (fun d -> d.name = "jerry") then print "hello"

as you can see, it reads almost the way you think:

if
exists
dogs
(fun d
->
d.name = "jerry") then print "hello"
ifthere existsa dogdsuch thatd.name = “jerry”) then print “hello”


End note:

In the above, the exists function is defined as follows:

let exists x y = List.exists y x

In the next episode I’ll deal with more complicated (but still very common) sentences and show how naturally they translate to F#.

_______
Microsoft Bizspark logoYellow blue soft is a proud Microsoft Bizspark partner. Tabbles (our flagship product) is developed entirely in F#, and WPF using Visual Studio 2010.

_______