What is Lambda Expression?

Introduction

In this article, I want to explain the main concepts of Lambda Expressions that sometimes they are misunderstood by many developers. Lambda Expressions are based on Lambda Calculus which was invented by Alonzo Church and Stephen Kleen in the 1930s. Today, they are supported by F#, Algol68, Python and Ruby.

Getting started with Lambda Expressions

First of all, let’s start by defining what a Lambda Expression is. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. An anonymous function is an inline statement or expression that can be used wherever a delegate type is expected. A delegate is a pointer to a function. An expression tree represents code in a tree-shaped structure where each node is an expression.

Let’s see two important Lambda Expressions: Function Delegate (Func) and Action Delegate (Action). Function Delegate (Funct) is a delegate that returns a value representing a function while Action Delegate (Action) is delegate that doesn’t return a value representing a method.

All lambda expressions use the lambda operator =>, which is read as “goes to“. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. That is, the expressions have the form of (input parameter) => expression or statement block. For example, the lambda expression x => x * x is read “x goes to x times x.”

Let’s see an example as shown in the Listing 1.

Func<int, int> func1 = x => x * x;

System.Console.WriteLine(func1(5).ToString());

System.Console.ReadLine();

Listing 1

And this is equivalent as the statements in the Listing 2.

static int Func1(int x)

{

return x * x;

}

System.Console.WriteLine(Func1(5));

System.Console.ReadLine();

Listing 2

Let’s see a Lambda Expression with statement block that is similar to the expression in Listing 1 as shown in the Listing 3.

Func<int, int> func1 = x => { return x * x; };

System.Console.WriteLine(func1(5).ToString());

System.Console.ReadLine();

Listing 3

Next example is the creation of an anonymous passing two parameters and returns the multiplication as shown in the Listing 4.

Func<int, int> func1 = x => { return x * x; };

System.Console.WriteLine(func1(5).ToString());

System.Console.ReadLine();

Listing 4

Conclusion

In this article, I’ve explained the concepts of Lambda Expressions with some examples.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s