Claudio Cherubino's blog Life of a Googler


Sorting odd and even numbers in F#

An Italian Microsoft Evangelist posted today a small programming exercise on his blog, presenting the solution with LINQ.

The exercise says (translated from Italian by me):

Given a list of unordered numbers (for instance 1, 7, 9, 2, 3, 4, 3, 4, 2, 3, 4, 5, 2, 0, 9), create a new list with all even numbers first and then all the odd ones.

The proposed solution also goes a little further, showing not only how to split the original list into odd and even numbers, but also putting them in the correct order, thus returning "022244413335799".

The following is the C# code used:

List<int> elenco = new List<int> { 1,7,9, 2, 3, 4, 3, 4, 2, 3, 4, 5, 2, 0, 9 };
var pariEdispari = elenco.OrderBy(s => s % 2 != 0);
var pariEdispariOrdinati = elenco.OrderBy(s => s % 2 != 0).ThenBy(s => s);

foreach (var item in pariEdispariOrdinati)

And now let's compare it with an F# approach:

let numbers = [ 1; 7; 9; 2; 3; 4; 3; 4; 2; 3; 4; 5; 2; 0; 9 ]

let result = numbers |> List.sort |> List.partition (fun x -> x % 2 = 0)

print_any ((fst result) @ (snd result))

As you can easily see, everything is done at line 4, where we apply twice the pipeline operator (|>).

This operator allows to chain functions, passing the output of one of them to the next one.
The same line could be written as:

List.partition (fun x -> x % 2 = 0) (List.sort numbers)

Line 6 is only used to print the result, but it has to take into account that the output of List.partition is a tuple, so we have to concatenate the two elements that can be retrieved with the fst (first) and snd (second) functions.

The @ operator actually concatenates the two lists.

I'm not sure that this is the best (and most elegant) solution, but I think that it is way ahead than any imperative solution, do you agree with me?

Comments (2) Trackbacks (3)
  1. The Italian Microsoft Evangelist has just closed comments for his post ( without any apparent reason probably because he don’t particularly appreciates comments…
    It is a typical Microsoft behaviour…?

  2. I’m not inside his mind but maybe he did that because the comments were not related anymore to the original post.

    By the way, in my opinion he didn’t attack anybody and I only see prejudices from your side when you write “typical Microsoft behaviour”…

    If you want to discuss in a mature way, why don’t you start signing with your name and surname as Pietro does?

Leave a comment