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
var adder = function (x) {
return function (y) {
return x + y;
};
};
add5 = adder(5);
add5(1) == 6
Scheme
(define adder
(lambda (x)
(lambda (y)
(+ x y))))
(define add5
(adder 5))
(add5 1)
6
Func> adder =
(int x) => (int y) => x + y; // `int` declarations optional
Func add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);
// Closure example
int yEnclosed = 1;
Func addWithClosure =
(x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);
As you can see from the snippet of Python and JavaScript, 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.