Practical functional programming

cover-image

I cringe when I see this sort of code:

var names = new List<string> { "tom", "dan", "warren" };

// Find the longest name in the list
//
var longest = names.First();  
foreach (var name in names) {  
    if (name.Length > longest.Length) {
        longest = name;
    }
}

Why is it so cringe-worthy? Because it's buggy and full of assumptions. Its very hard to write code like that this that isn't buggy, and really this is grade 11 style programming (no disrespect to any talented grade 11'ers out there!).

Mainstream languages (e.g. Java, C#, etc) are introducing more and more features which promote a functional programming paradigm and when used correctly can rid the world of this style of code.

.NET developers who use LINQ and Lambda expressions have been doing it (possibly unknowingly) for years, and writing nice clean code by making use of higher-order functions:

var names = new List<string> { "tom", "dan", "warren" };

// Find the longest name in the list
//
var longest = names  
                .OrderByDescending((name) => name.Length)
                .First();

Console.Out.WriteLine ("The longest name is: {0}", longest);  

This version is so much safer - and much simpler to understand. There is no mutation occurring either. Either the variable longest exists or it doesn't. No halfway state while the code is running.

Use this stuff! You can find equivalents in most mainstream languages, my favourite being prelude for livescript.