Functional Programming Comparison

Seem­ingly late to the prom, Microsoft is adding lambda expres­sions to C# 3.0. For those of you unfa­mil­iar with lambda expres­sions, they are basi­cally just syn­tac­tic sugar for cre­at­ing anony­mous func­tions that you can pass around. Func­tional lan­guages like Lisp and to a lesser degree, Python, have had them from day 1. In these lan­guages, func­tions are treated as first class mem­bers, not bas­tard step-children of the language.

Anony­mous func­tions are use­ful for a vari­ety of rea­sons that Joel sum­ma­rizes nicely.

Let’s com­pare how lambda expres­sions are done in C# 2.0 (anony­mous meth­ods), in C# 3.0 (lambda expres­sions) and Python.

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

Note the del­e­gate key word as well as the typ­ing of the func­tion done by “Func” which basi­cally says I’m declar­ing a func­tion with an inte­ger para­me­ter 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 sim­i­lar though much eas­ier on the eye:
Func f1 =i=>i+1;

Much sim­pler, lost the del­e­gate key­word and con­sid­er­ably eas­ier to grok. Still though, because we’re deal­ing with a sta­t­i­cally typed lan­guage, you have to jump through some seri­ous hoops, i.e. the “Func” typ­ing.

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

Mmm, that’s much eas­ier to under­stand. You have one key­word, lambda and away you go. The lack of typ­ing makes this faster to write as well as eas­ier to under­stand. The more I branch out into alter­na­tive lan­guages, the more I won­der what ben­e­fit we get from sta­t­i­cally typed lan­guages like C# over a dynam­i­cally typed lan­guage like Python. Obvi­ously, you get some ben­e­fit by hav­ing the com­piler pick up typ­ing errors but is that a big enough ben­e­fit to off­set the gains in pro­duc­tiv­ity you get from a dynam­i­cally typed lan­guage? I kind of doubt it but I’d be inter­ested in stud­ies about it.

Under­stand, dynam­i­cally typed does not mean “not-strongly typed”. Python still has typ­ing, it’s just done at run time. So your tests are going to catch 80–90% of the issues com­monly related to “no typing”.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *