A few weeks ago, some of my colleagues and I were discussing the idiosyncrasies of various programming languages (as we often find ourselves doing—we’re kind of geeky that way), when one of us pointed out that the following code is completely valid C++0x syntax:
The “operator soup”1 above defines a C++ lambda expression (denoted by the square brackets) which declares no parameters (the first empty parentheses) or body (the empty curly braces) and is immediately invoked (the final parentheses). Conceptually, this is a nop—an empty lambda that is immediately invoked.
We found ourselves fascinated by this idea of a do-nothing lambda, and went ahead to define the same thing in our respective languages. Our first attempt was C#.
While the code above looks quite pretty, it’s not exactly legal. In C#, lambdas must always have an explicit delegate type, so an ugly type-cast is required in order to compile:
Sigh, so close, yet so dissatisfying!
The stronger notion of type inference in F# allows for much more succinctness.2
However, my favorite version is written in Visual Basic 10.
What it lacks in succinctness,3 it makes up for with human-readable clarity.
How do you write a do-nothing lambda in your language?
1One could also declare the square brackets with either an = or & operator inside to define how variables that are declared in the same scope as the lambda are captured within the lambda function’s closure. It’s amazing how much one can do without typing a single identifier character!
2Note that the F# example contains a subtle difference from the others in that it returns a value of type Unit. This implies that the entire F# expression could be passed as an argument to another function, but that is not true of the other examples.3Though it’s the same size as the C# version when unnecessary whitespace characters are removed.
Page rendered at Sunday, May 19, 2013 6:10:02 AM (Pacific Standard Time, UTC-08:00)
If feel a bit behind and need to catch up on WPF, this is the book.
Great book on F# containing from Beginner to Advanced. It even has chapters on more arcane features of the language, such as Computation Expressions and Quotations.
Because this book provides source code in Standard ML, it's a fantastic resource for learning F#. One bit of warning: this book does not teach classic data structures. While structures such as binomial heaps and red-black trees are presented, it is assumed that the reader already knows and understands them.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.