Since the next semester will be spend learning some C#, I spend some time researching the language. I came across the term lambda expression, which in terms i an anonymous function or method, it is very similar to lambda calculus which is a way of expressing anonymous functions.

Some of the simpler ways to use these expressions are something like this:

first of we define a delegate, for instance:

delegate int multiply (int a, int b);

an example (static) implementation in lambda expression would be:

multiply multi_impl = (int a, int b) => a * b;

Such uses can be a bit dull, lambda expressions lack recursive behavior, much like lambda calculus is though to do, but using the generic Func class in System.Core one can create a Func object which references a method of itself thereby creating recursion. Here's an example of a fibonacci calculation:

First the recursive part:

Func<long, object, long> fibonacci_impl = (i, func) => i == 0 ^ i == 1 ? i :
    ((Func<long, object, long>)func)(i - 2, func) +
    ((Func<long, object, long>)func)(i - 1, func);

The object in the middle is the function itself, however since it cannot reference itself explicit we do it this way and start the recursion from another expression, which can be found below:

Func<long, long> fibonacci = i => i < 0 ? -1 : fibonacci_impl(i, fibonacci_impl);

It is important to notice that the fibonacci method only takes one argument and starts the function above that one with the integer and the function itself, moreover the casts from object to fibonacci_impl is necessary since fibonacci_impl is unable to reference itself in the expression.

I some benchmarking comparing it to a normal recursive function, and the normal way is faster. I realize that lambda expressions aren't meant for recursion just yet, but is another way to minimize code when implementing anonymous methods. It still fun to mess with however =)

For more on lambda calculus:

Under the "recursion and fixed points" section there is the same way of doing recursion, but in lambda calculus. And as is written:

"In lambda calculus, one cannot define a function which includes itself. To get around this, one may start by defining a function, here called g, which takes a function f as an argument."