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. |

_______

Hi there,

I was looking forward your next F# sample.

I like this one 🙂

Just for fun, here is how it can look in C#:

if (dogs.GroupBy(dog => dog.name).Where(group => group.Count() > 1).Any()) Console.Write(“hello”);

You can read it as: Create groups of dogs, such that in each group are dogs with the same name. If there is any group with more than one dog, then print “hello”.

Excellent post. This is something I’ve been trying to get across in conversations and in my own blog: that F# looks like what is does. I think that’s one of the reasons F# is becoming so popular in communities like science and finance, where programming is used as a means rather than an end in itself.