Functional Programming Comparison

Seemingly late to the prom, Microsoft is adding lambda expressions to C# 3.0. For those of you unfamiliar with lambda expressions, they are basically just syntactic sugar for creating anonymous functions that you can pass around. Functional languages like Lisp and to a lesser degree, Python, have had them from day 1. In these languages, functions are treated as first class members, not bastard step-children of the language.

Anonymous functions are useful for a variety of reasons that Joel summarizes nicely.

Let’s compare how lambda expressions are done in C# 2.0 (anonymous methods), in C# 3.0 (lambda expressions) and Python.

In 2.0, an anonymous method would look like this:
Func f1 = delegate(int i){return i + 1;}

Note the delegate key word as well as the typing of the function done by “Func” which basically says I’m declaring a function with an integer parameter of int and a return of int. You could then call f1 like this: int a = f1(1) and get 2.

In 3.0, it’s similar though much easier on the eye:
Func f1 =i=>i+1;

Much simpler, lost the delegate keyword and considerably easier to grok. Still though, because we’re dealing with a statically typed language, you have to jump through some serious hoops, i.e. the “Func” typing.

In Python, we get this: f1 = lambda i: i + 1

Mmm, that’s much easier to understand. You have one keyword, lambda and away you go. The lack of typing makes this faster to write as well as easier to understand. The more I branch out into alternative languages, the more I wonder what benefit we get from statically typed languages like C# over a dynamically typed language like Python. Obviously, you get some benefit by having the compiler pick up typing errors but is that a big enough benefit to offset the gains in productivity you get from a dynamically typed language? I kind of doubt it but I’d be interested in studies about it.

Understand, dynamically typed does not mean “not-strongly typed”. Python still has typing, it’s just done at run time. So your tests are going to catch 80-90% of the issues commonly related to “no typing”.