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:
Note the delegate key word as well as the typing of the function done by “Func
In 3.0, it’s similar though much easier on the eye:
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
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”.