Lambda Functions


Published on February 25th, 2009

1 Comment

What about those predicate, conversion, and aggregation functions? Does this style of programming with higher order functions mean you have to write a bunch of tiny functions to pass around? Nope! We can use C# lambda functions.

A lambda function is a function defined on-the-fly at the call site without a lot of declaration and syntax baggage. Here’s a sample lambda function that replaces the isOver30 function from the Filter post…

List<T> untrustworthy = employees.Filter( emp => emp.Age > 30 );

That’s the expression form of lambda function. To the left of the => symbol is the parameter list, multiple parameters are wrapped in parenthesis and separated by commas. (ie. (a, b) => example below). To the right of the => symbol is the expression, which can refer to the parameter by name.

Lambdas can also have statement bodies if needed…

List<t> untrustworthy = employees.Filter( emp =>
        {
            // untrustworthy indeed
            if( emp.LastName == "Page" )
                emp.Age /= 2;
            return emp.Age > 30;
        };

Lambda functions with statement bodies have their place…but this doesn’t seem to be one of them from a code clarity point of view. Choosing to use a lambda function will depend on whether the function is generally useful or whether it will be called from multiple locations. Why bother cluttering up your class’s interface with yet another method declaration when a lambda will do the trick? Lambda functions also let you place details in-line rather than hiding them.

Here’s a few quick examples of Reduce used with lambda functions that take multiple parameters.

Reduce(list, 0, (x, y) => y + 1); //A
Reduce(list, 0, (x, y) => x + y); //B
Reduce(list, 0, (x, y) => (x > y) ? x : y; //C

Can you guess what they do?

The first call, A, ignores the x parameter altogether, it simply increments the result y (initially 0) by 1 for each element. It will give a COUNT of the number of items in the list. Yes, that’s an O(n) count function, I’m proud. The second call, B, adds each item x to the accumulated sum in y…it’s a SUM function. The last call, C, returns the greatest value in the sequence, or MAX. (MIN is left as an exercise for the reader, ha!)

These are among the simplest reduce functions, we’ll include them in FinQ as part of the basic statistics functions (upcoming post). The implementations also reveal limitations in C#’s functional programming features, more to come on that topic for certain. But first, let’s take another look at Reduce, one that I hope you’ll find interesting.


Comments

One Response to “Lambda Functions”

  1. Weekly Link Post 85 « Rhonda Tipton’s WebLog Says:

    [...] Sam Page has posted a great article on Lambda Functions. [...]

Leave a Reply