Jump to content

Lambda (programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 131.107.0.81 (talk) at 17:43, 13 December 2011. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Lambda is an operator used to denote anonymous functions or closures, following the usage of lambda calculus, in programming languages such as C#, Erlang, Lisp, Python, Ruby, Scala, and recently C++11, the latest iteration of C++.

Examples

C#

In C#, lambda expressions are often used with LINQ:

var allWikipediaPages = GetAllWikipediaPages();
var lambdaWikipediaPage = allWikipediaPages.First(wp => wp.Title == "Lambda (programming)");

C++

In C++, lambda expressions can take this form:

auto square = [] (int x) -> int { return x * x; };
square(5); // returns 25

Erlang

In Erlang, lambda expressions (usually called as "funs") can take this form:

F = fun(X) -> X * X end,
F(5). % returns 25

Haskell

In Haskell, lambda expressions can take this form:

Prelude> let f = \x -> x + 1
Prelude> :t f
f :: Integer -> Integer
Prelude> f 2
3

Python

In Python, an example of this use of lambda is this sample of computer code that sorts a list alphabetically by the last character of each entry:

>>> stuff = ['woman', 'man', 'horse', 'boat', 'plane', 'dog']
>>> sorted(stuff, key=lambda word: word[-1])
['horse', 'plane', 'dog', 'woman', 'man', 'boat']

Scala

In Scala, lambda expressions can take this form:

scala> (x:Int, y:Int) => x + y
res0: (Int, Int) => Int = <function2>
scala> res0(1, 2)
res1: Int = 3

Argument types can be inferred when applied to a list:

scala> List(1, 2, 3, 4)
res0: List[Int] = List(1, 2, 3, 4)
scala> res0.foldLeft(0)((x, y) => x + y)
res1: Int = 10