Lambda expressions are similar to anonymous functions in other languages.
Lambda expressions are open formulas which also specify variables which are to be bound. Evaluation (finding the value of a function call) is then achieved by substituting the bound variables in the lambda expression's body, with the user supplied arguments. Put simply, lambda expressions allow us to express functions by way of variable binding and substitution.
Lambda expressions look like
\x -> let {y = ...x...} in y
Within a lambda expression, the variables on the left-hand side of the arrow are considered bound in the right-hand side, i.e. the function's body.
Consider the mathematical function
f(x) = x^2
As a Haskell definition it is
f x = x^2
f = \x -> x^2
which means that the function f
is equivalent to the lambda expression \x -> x^2
.
Consider the parameter of the higher-order function map
, that is a function of type a -> b
. In case it is used only once in a call to map
and nowhere else in the program, it is convenient to specify it as a lambda expression instead of naming such a throwaway function. Written as a lambda expression,
\x -> let {y = ...x...} in y
x
holds a value of type a
, ...x...
is a Haskell expression that refers to the variable x
, and y
holds a value of type b
. So, for example, we could write the following
map (\x -> x + 3)
map (\(x,y) -> x * y)
map (\xs -> 'c':xs) ["apples", "oranges", "mangos"]
map (\f -> zipWith f [1..5] [1..5]) [(+), (*), (-)]