December 12, 2009

Lambda Examples

In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion.

An anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier. Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus.

In C# lambda expression can be written as:

x=>x+1;

Here left part is paramter where as right is expression. The same can be written as:

int func(int x){
  return x+1;
}

// Some examples - 

x , y => x* y;
() => x; // valid but not useful!


Lambda expression & Lambda statement block
x => 2 * x;    // this is a expression
y => {return 2*x; } // this is a statement block
Delegate & Lambda Func
Following delegate is same as Func lambda expression:
<int> funcDelegate = delegate(int x)
{
return x + x;
};

Func<int> lambda = x => x + x;

Console.WriteLine(funcDelegate(10));
Console.WriteLine(lambda(10));
// above lambda can also be written as:
<int> lambda = (int x) => x + x;
Example: Lambda expressions takes a string & returns void
// A delegate that takes a string and returns void
public delegate void OutputToConsole(string arg);

static void Main(string[] args)
{
OutputToConsole op = a => {
Console.WriteLine(a);
};
op("Hello, World");
}
Example: Lambda – takes nothing returns void
// A delegate that takes no arguments and returns void
public delegate void OutputHelloToConsole();

static void Main(string[] args)
{
OutputHelloToConsole op = () =>
{
Console.WriteLine("Hello, World");
};
op();
}