Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain lambda expressions? [duplicate]

Tags:

I don't really get lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the => syntax, people in my world (.NET) are talking about lamdba expressions more and more.

I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing?

Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.

like image 993
Robert S. Avatar asked Oct 09 '08 14:10

Robert S.


People also ask

Can we reuse lambda expression?

Fortunately, you can assign lambda expressions to variables and reuse them, as you would with objects.

How do you remove duplicates in lambda expression?

Let us look at the new JDK 8 lambda expressions and Stream api's distinct() method to remove duplicates. distinct() method internally calls equals() method on each value and filters the duplicates objects. In our example, we are adding Strings to the list so equals() method of String class will be called.

Can a lambda function have multiple expressions?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Can a lambda statement have more than one statement?

The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.


1 Answers

Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now).

In C# 1 we could only create delegate instances from normal methods. In C# 2 we gained anonymous methods. In C# 3 we gained lambda expressions, which are like more concise anonymous methods.

They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ:

                       // Only include children - a predicate var query = dataSource.Where(person => person.Age < 18)                         // Transform to sequence of names - a projection                       .Select(person => person.Name); 

There's a fuller discussion of this - along with other aspects - in my article on closures.

like image 72
Jon Skeet Avatar answered Sep 27 '22 17:09

Jon Skeet