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
As you can see from the snippet of Python, 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.
Examples in other languages
Perl 5
sub adder {
my ($x) = @_;
return sub {
my ($y) = @_;
$x + $y
}
}
my $add5 = adder(5);
print &$add5(1) == 6 ? "ok\n" : "not ok\n";
JavaScript
var adder = function (x) {
return function (y) {
return x + y;
};
};
add5 = adder(5);
add5(1) == 6
JavaScript (ES6)
const adder = x => 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
C# 3.5 or higher
Func<int, Func<int, int>> adder =
(int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> 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<int, int> addWithClosure =
(x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);
Swift
func adder(x: Int) -> (Int) -> Int{
return { y in x + y }
}
let add5 = adder(5)
add5(1)
6
PHP
$a = 1;
$b = 2;
$lambda = fn () => $a + $b;
echo $lambda();
Haskell
(\x y -> x + y)
Java see this post
// The following is an example of Predicate :
// a functional interface that takes an argument
// and returns a boolean primitive type.
Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
boolean result = pred.test(4); // true
Lua
adder = function(x)
return function(y)
return x + y
end
end
add5 = adder(5)
add5(1) == 6 -- true
Kotlin
val pred = { x: Int -> x % 2 == 0 }
val result = pred(4) // true
Ruby
Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.
def adder(x)
lambda { |y| x + y }
end
add5 = adder(5)
add5[1] == 6
Ruby being Ruby, there is a shorthand for lambdas, so you can define adder
this way:
def adder(x)
-> y { x + y }
end
R
adder <- function(x) {
function(y) x + y
}
add5 <- adder(5)
add5(1)
#> [1] 6
Closures, lambdas, and anonymous functions are not necessarily the same thing.
An anonymous function is any function that doesn't have (or, at least, need) its own name.
A closure is a function that can access variables that were in its lexical scope when it was declared, even after they have fallen out of scope. Anonymous functions do not necessarily have to be closures, but they are in most languages and become rather less useful when they aren't.
A lambda is.. not quite so well defined as far as computer science goes. A lot of languages don't even use the term; instead they will just call them closures or anon functions or invent their own terminology. In LISP, a lambda is just an anonymous function. In Python, a lambda is an anonymous function specifically limited to a single expression; anything more, and you need a named function. Lambdas are closures in both languages.
Best Answer
Functions without a name
Simply put, a lambda is a function without a name, or an anonymous function. A small piece of executable code, that can be passed around as if it were a variable. In JavaScript:
Let's see now some uses for these lambdas.
Abstracting boilerplate code
Lambdas may be used to abstract away boilerplate code. For example loops. We're used to write
for
andwhile
loops all day long. But this is code that does not be written. We could extract the code inside the loop, the most important part of the loop, and abstract away the rest:by using the
forEach
of array objects, becomes:The above abstraction may not be that useful, but there are other higher order functions, like
forEach
, that perform much more useful tasks. For examplefilter
:Code execution delay
In some environments, in which the concept of event is available, we could use lambdas to respond to events that may happen at some point in time.
This could have been done in some other ways, but those are rather verbose. For example, in Java there's the
Runnable
interface.Factories of functions
Until this point, we only used lambdas for its syntactic sugar capabilities mostly. But there are situations where lambdas can be much more useful. For example we may have functions that return lambdas. Let's say we have a function that we want its return values to be cached.
Later on, we may notice that we have a similar function:
There's clearly a pattern in there, so let's abstract it away. Let's use memoization.
As you can see, by using lambdas, we were able to abstract away the caching/memoization logic. If for the other example there were some workarounds, I believe that this particular problem is hardly solved using other techniques. We managed to extract some important boilerplate code into a single place. Not to mention that we got rid of the
users
andphotos
global variables.Looking at your profile I see that you're mostly a Python user. For the above pattern, Python has the concept of decorators. There are lots of example on the net for memoization decorators. The only difference is that in Python you most likely have a named nested function inside that decorator function. The reason being that Python only support single-expression lambdas. But the concept is the same.
As an example of Python lambda use. The above code in which we filtered even numbers can be represented in Python like this:
Anyway, lambdas are not that powerful without closures. Closures is what makes the concept of lambdas so powerful. In my memoization example I have used closures to create a closure around the
store
param. This way, I have access to that param even after thememoize
function has returned its result (a lambda).