tags:

views:

484

answers:

6

I am fairly new to programming and while doing a lot of reading this concept of a lambda keeps coming up but I'm having a hard time putting my finger on what it actually is and how implementing it will make my programming life so much better. So first, what is a lambda and second how might it be implemented?

Thanks to all who posted. As has been mentioned in the comments, this is a duplicate, but there are so many great answers here I want to preserve them for the community so I'm turning it into a community post. Here is the link to the other question:

http://stackoverflow.com/questions/16501/what-is-a-lambda-function

+1  A: 

Lambda is lambda calculus, but I think people use it with the term closure interchangeably. See What is a Closure?

Ruby's implementation is easy to understand and very powerful. In the following code times method accepts a block of code between the curly braces and calls it back HEIGHT times. You can define similar method that accepts a block of code and implement looping construct-ish things.

@cells = []
HEIGHT.times { @cells << empty_row }

I guess it's more interesting if there's a parameter.

5.times { |i| puts i, " " }
eed3si9n
A: 

Lambda means different things to different languages. I know about them in the context of python, but I've heard that python has a different approach than other languages.

Essentially, in python, a lambda is an anonymous function that can only consist of a single expression, the result of which is returned.

I understand that in other languages, they are more generalized anonymous functions, without the single expression limitation, but I'm not certain about the details.

An anonymous function, is just what it sounds like. A function without a name. For example, they are frequently used as event handlers, or any case in which you need a simple callback function, but don't want to clutter up the namespace.

recursive
+7  A: 

A lambda is an inline description of a function. It has originated from functional programming languages and the number of other languages that support something like it is growing these days. The name comes from a mathematical thing called Lambda calculus which has influenced functional programming languages (such as Lisp) and the idea of lambdas come from it.

Your question depends on the programming language you're talking about. For instance, in F#, you would use fun x -> x * x to represent

int myfunction(int x) { return x * x; }

In C#, you would use x => x * x to represent the same function. How it's used and what you can do with it pretty much depends on the language you are working in.

Talking about C#, the great thing about them is the ability to parse them as expression trees. A lambda expression can be used as a code, like a delegate (roughly a function pointer) or as data, in an expression tree. Using them as expression trees, make libraries such as LINQ to SQL to be able to use the expression to create a SQL statement in order to submit to server and get the appropriate results.

Mehrdad Afshari
+3  A: 

lambda in the programming world means an anonymous function that can be passed and returned like every other normal variable. So-called functional languages have them builtin but recently there is a growing set of languages supporting them, since they allow writing reusable code. See this for example, written in the next version of C++:

// write this once...
int transform_values(int * values, int n, function<int(int)> f) {
    for(int i = 0; i < n; i++)
        values[i] = f(values[i]);
}

int values[] = { 1, 2, 3, 4 };
// ... then call it to double the values in an array
transform_values(values, 4, [](int v) { return v * 2; });

It does look similar in C# and other languages supporting lambdas. Now there is the word "closure". It means that a lambda can capture local variables and use them in the computation of its result:

int local_variable = 5;
int values[] = { 1, 2, 3, 4 };
// ... then call it to multiply the values in an array
transform_values(values, 4, [=](int v) { return v * local_variable; });

The variable local_variable is now captured inside the closure and can be used within it. Variables may also be updated by a closure. Lambdas are a basic building block of functional languages. Here is an example in haskell:

map (\x -> x * 2) [1, 2, 3, 4]

Will do the same as the C++ code above. It maps the values in the list using the given function (a lambda here) into a result list. Using haskell, you can see nicely how the syntax used maps to the mathematical notion of Lambda Calculus.

Johannes Schaub - litb
yesraaj
+4  A: 

Lambda is a means of creating an anonymous function or closure. In imperative languages (and functional ones) it is equivalent to allowing nested functions where the inner function has access to local variable and parameters of the enclosing function. It is found in functional languages under the keywords lambda, fun, fn or even \; in Smalltalk it is called a block. It is also found in most scripting languages, e.g., Perl, Python, Lua, etc.

About the only languages without lambda are

  • Languages without nested functions, like Standard C or Icon

  • Languages with second-class nested functions---a function may not be returned from a function, stored in a global variable, or stored in a heap-allocated data structure. This language family includes Pascal and its descendants in the Modula, Ada, and CLU families.

Lambda has important implications for programmers and compiler writers: it is no longer possible to store all local variables on a stack. Instead some variables may be captured and stored in a heap-allocated closure. Be aware that when you write lambda you are writing an allocation.

Example: one of the simplest functions is composition (Haskell syntax):

compose f g = \x -> f (g x)

This says that compose takes two functions f and g as arguments, and it returns an anonymous function which takes its argument x and then applies g and then f to x. An application of compose creates a closure allocated on the heap which stores the value of f and g as well as a pointer to code for the body of the lambda. In languages where lambda is common, such as Haskell, ML, Caml, and Scheme, a great deal of effort has been expended making allocation blindingly fast. Some scripting languages, such as Lua, have unusual implementations which make the non-lambda case the same as in an imperative language, while also making lambda reasonably fast. Lambda is also fast in Smalltalk, which was also designed to allocated lots of objects on the heap. In languages where lambda was retrofitted, like Perl or Java (inner classes are related to lambda), the expense can be relatively much higher.

In general, if a language was designed with lambdas in mind, you can use them as much as you like. Especially in ML, Caml, Scheme, Haskell, even anonymous functions are dirt cheap---use lots of them!

Norman Ramsey
nice overview. In next c++, though, it will create an object allocated on the stack that will have references to local variables, or alternatively hold copy of those (lambda lifetime must be longer, copies need to be done) and have operator() overloaded. no performance lost will be noticeable there.
Johannes Schaub - litb
You don't have to wait for the next C++; there's the perfectly stunning FC++ library: http://www.cc.gatech.edu/~yannis/fc++/
Norman Ramsey
+4  A: 

Lambda are hard to catch, but once you have pictured them, you cannot understand why you didn't get it before.

Lamdba are anonymous functions

Lambda are ordinary functions, the only difference is that you don't give them a name.

To understand that, you must know first that when you create a function, the code is stored in memory at an address only knowned by the computer.

So when you do something like that :

function Foo ()
{
 /* your code here */
}

What you really do is binding the name "Foo" to the adress of the code in memory.

Now, there is an other way to access an address : references (and pointers, but let's skip this nasty guys)

Well, a lambda function is a function that have no name, so it can be only access with its reference.

How do you use them ?

When you create a lambda function, you usually plan to use it only once.

The step by step process is usually :

  1. Create the function
  2. Get the reference
  3. Pass the reference somewhere it will be used

Finally, the reference is lost, and so the function is destroyed automatically.

The typical use case is a callback function. You declare, create and pass the function in one row, so it's handy.

Example from the real word

In Python, you can use lambda in list comprehensions :

/* create a list of functions */
function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]

In Javascript, you usually pass a function to others functions. Example with JQuery :

 $("img").each(

 /* here we pass a function without any name to the "each()" method   */

 function(i){  his.src = "test"   i   ".jpg"; }

 );

The things you'd better know

  • Some languages, like Javascript or Lisp, make a massive use of lambdas. It can be for cultural reason, but the functional programming paradigm tends to lead to lambda-mania.

  • Long lambdas make the code hard to read. That's why some languages restrain the possibilities of lambdas, such as Python that does not allow "if" statement in them.

  • Lambdas are just normal functions. Where ever you use one, you can use an ordinary function instead. It's just a matter of coding style.

e-satis
I accepted this answer because it was the clearest answer for my noob mind. All the other answers were outstanding as well.
Mike Farmer
-1. Lambdas are not always functions. At least in C#, you can treat them as expression trees. In that cases, like LINQ to SQL, it's not possible to use functions instead. Treating them as data is what makes them special in languages such as Lisp and even C#.
Mehrdad Afshari
Yep, but how do you explain that to somebody that never used lisp or LINQ with simple words ? Good luck.
e-satis