This is the second episode of a series meant to illustrate how functional languages, and in particular F#, allow us to write code in a more natural way with respect to imperative languages. Here is the previous episode.
Let us deal with a slightly more complicated condition:
|if there are two dogs with the same name, print „hello“|
Again, this sentence reflects the way we think. I am now going to show you how to gradually and naturally translate it to F#.
Let us rephrase the sentence as
|if there exist two dogs D1 and D2 such that D1 and D2 have the same name, then print „hello“|
As you can see, the word „exist“ highlights two different dogs at once, i.e. a pair of dogs (taken from the set of all pairs of dogs). Translating this sentence in F# would require us to generate all pairs of dogs, in order to pick a pair. Since we do not want to have to do that for now, it is easier to use the logical rule:
|â??x,y: P â?? â??x: â??y: P|
or, in english,
|There exists x and y such that P is true â?? There exists x such that there exists y such that P is true.|
This logical rule allows us to rephrase the sentence in such a way that „exists“ highlights a single dog. Here is the rewritten sentence:
|if there exists a dog D1 such that there exists another dog D2 such that D1 and D2 have the same name, then print „hello“|
This sentence is easier to translate to F#. However, we are not done: we have to add a condition expressing something we tend to give for granted, namely the fact that D1 and D2 are different dogs. (Otherwise the above condition will always evaluate to true.) So our sentence becomes:
|If there exists a dog D1 such that there exists a dog D2 such that D1 and D2 have the same name and D1 is different from D2, then print „hello“|
And we are done. The F# code is almost identical:
|if exists dogs (fun d1 -> exists dogs (fun d2 -> d1.name = d2.name && d1 <> d2 )) then print „hello“.|
(where the exists function is defined as in the previous episode)
See you in the next episode!
|Yellow blue soft is a proud Microsoft Bizspark partner. Tabbles (our flagship product) is developed entirely in F#, and WPF using Visual Studio 2010.|