views:

6021

answers:

12

Hey guys, I see this term being used a bit, and a Google search didn't quite yield the most clarity, so help me out: for a person without a comp-sci background, what is a lambda in the world of Computer Science?

UPDATE:

marxidad, thanks for the reply--it seems to be climbing up in everyone's favor, so I'll likely accept it soon. Do you have any "real-life" examples, possibly in a few languages (perhaps in one that doesn't use the lambda keyword, too)?

+21  A: 

It refers to the lambda calculus which is a formal system that just has lambda expressions, which represents a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type.

Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:

(lambda (x y) (* x y))

It can be applied in-line like this (evaluates to 50):

((lambda (x y) (* x y)) 5 10)
Mark Cidade
+2  A: 

You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function

mercutio
+56  A: 

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.

Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.

Python

def adder(x):
    return lambda y: x + y
add5 = adder(5)
add5(1)
6

Javascript

adder = function (x) {
    return function (y) {
        x + y
    }
};
add5 = adder(5);
add5(1) == 6

Scheme

(define adder
    (lambda (x)
        (lambda (y)
           (+ x y))))
(define add5
    (adder 5))
(add5 1)
6

As you can see from the snippet of python and js, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.

mk
This is by by far the best yet simplest description of lambda I have ever seen. Yet you managed to not lose any of the key ideas bravo. +1
faceless1_14
Agreed. I have seen the light! Thanks. =)
Chris Cooper
+1 Best explanation I've seen. Thanks
Rich
awesome, thanks much
Orbit
+19  A: 

A lambda is a type of function, defined inline. Along with a lambda you alsu usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.

For instance, here's a C# piece of code that doesn't use a lambda:

public Int32 Add(Int32 a, Int32 b)
{
    return a + b;
}

public Int32 Sub(Int32 a, Int32 b)
{
    return a - b;
}

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, Add);
    Calculator(10, 23, Sub);
}

This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.

In C# 2.0 we got anonymous methods, which shortens the above code to:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a + b;
    });
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a - b;
    });
}

And then in C# 3.0 we got lambdas which makes the code even shorter:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, (a, b) => a + b);
    Calculator(10, 23, (a, b) => a - b);
}
Lasse V. Karlsen
+1 for being simple/direct and to the point,helped me understand "lambda" in the 3mins it took me to read the answer
Madi D.
I liked the way you presented it.
ragu.pattabi
A: 

It is a function that has no name. For e.g. in c# you can use

numberCollection.GetMatchingItems<int>(number => number > 5);

to return the numbers that are greater than 5.

number => number > 5

is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.

Serhat Özgel
+2  A: 

I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.

Their quick explanation: Lambdas are a way to treat code (functions) as data.

Jon Galloway
+5  A: 

Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.

In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.

For instance (in C#3):

LinqToSqlContext.Where( 
    row => row.FieldName > 15 );

LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.

The statement above becomes:

select ... from [tablename] 
where [FieldName] > 15      --this line was 'read' from the lambda function

This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.

Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:

LinqToSqlContext.Where( 
    row => SomeComplexCheck( row.FieldName ) );

Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through SomeComplexCheck.

Lambda functions should not be confused with anonymous methods. For instance:

LinqToSqlContext.Where( 
    delegate ( DataRow row ) { 
        return row.FieldName > 15; 
    } );

This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.

Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.

Keith
A: 

An example of a lambda in Ruby is as follows:

hello = lambda do
    puts('Hello')
    puts('I am inside a proc')
end

hello.call

Will genereate the following output:

Hello
I am inside a proc
CodingWithoutComments
+1  A: 

@Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:

string[] GetCustomerNames(IEnumerable<Customer> customers)
 { return customers.Select(c=>c.Name);
 }

Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:

getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});

The interesting thing with C#'s lambda syntax, though, is that on their own their type cannot be infered (i.e., you can't type var foo = (x,y) => x * y) but depending on which type they're assigned to, they'll be compiled as delegates or abstract syntax trees representing the expression (which is how LINQ object mappers do their "language-integrated" magic).

Lambdas in LISP can also be passed to a quotation operator and then traversed as a list of lists. Some powerful macros are made this way.

Mark Cidade
A: 

I have trouble wrapping my head around lambda expressions because I work in Visual FoxPro, which has Macro substitution and the ExecScript{} and Evaluate() functions, which seem to serve much the same purpose.

? Calculator(10, 23, "a + b")
? Calculator(10, 23, "a - b");

FUNCTION Calculator(a, b, op)
RETURN Evaluate(op)

One definite benefit to using formal lambdas is (I assume) compile-time checking: Fox won't know if you typo the text string above until it tries to run it.

This is also useful for data-driven code: you can store entire routines in memo fields in the database and then just evaluate them at run-time. This lets you tweak part of the application without actually having access to the source. (But that's another topic altogether.)

SarekOfVulcan
+5  A: 

The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.

A simple example (using Scala for the next line) is:

args.foreach(arg => println(arg))

where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):

void printThat(Object that) {
  println(that)
}
...
args.foreach(printThat)

except that you don't need to bother with:

  1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
  2. Naming something that you're only using once.

Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:

int tempVar = 2 * a + b
...
println(tempVar)

instead of just writing the expression where you need it:

println(2 * a + b)

The exact notation varies from language to language; Greek isn't always required! ;-)

joel.neely
+1 - The most succinct and clear explanation of this I've ever come across.
Ali Parr
A: 

Basicly in Javascipt for example functions are treated as the same mixed type as everything else (int, string, float, bool) as such you can create functions on the fly, assign them to things, and call them back later. Its usefull but kinda not somthing you wana over use or u confuse everyone whos got to maintain your code after you...

This is some code i was playing with to see how deep this rabit hole goes...

var x = new Object;
x.thingy = new Array();
x.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }
x.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }
x.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }

for(var i=0 ;i<3; i++)
 x.thingy[i]()()();

`