Saturday, February 7, 2009

Fun With Functional Programming

Functional programming is seeing a lot of support these days so I thought I'd examine the differences between a few languages for common tasks. In this example, I want to search a list of numbers for only the even ones.

Here is how it can be done in C#:

int[] fullList = { 4, 31, 24, 2, 1, 13, 56 };
int[] evens = Array.FindAll(fullList, x => (x % 2 == 0));
Array.ForEach<int>(evens, x => Console.WriteLine(x.ToString()));

Now in F#
let fullList = [4; 31; 24; 2; 1; 13; 56]
let evens = fullList > List.filter (fun x -> (x % 2 = 0) ) > List.to_array
do Array.ForEach(evens, (fun x -> printfn "%d" x))

Pretty similar as you can see. Now lets see it in Ruby:

fullList = [ 4, 31, 24, 2, 1, 13, 56]
evens = fullList.select { x (x % 2 == 0)}
puts evens

Nice and simple. For comparison's sake, let's look at the non functional way of doing this in C# (I will use C# 2.0 here to make it at least a little easier):

int[] fullList = { 4, 31, 24, 2, 1, 13, 56 };
List<int> evens = new List<int>();
foreach (int num in fullList)
{
if (num % 2 == 0)
evens.Add(num);
}
foreach (int n in evens)
Console.WriteLine(n);

Functional programming offers great benefits when it comes to simplifying code and you aren't too limited to in your choice of languages to do it in. Granted there will be bigger differences when using more complicated examples but its nice to see how available it has become.