🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Lambdas

A lambda is a function with no name. It is written in the place where a function is needed.

A lambda can be applied at once

The lambda sits in brackets and is applied to 4 at once. It doubles 4, and print shows the result.

main :: IO ()
main = print ((\x -> x * 2) 4)

A binding can hold a lambda

The binding double holds the lambda. Using double 7 applies that lambda to 7.

double = \x -> x * 2

main :: IO ()
main = print (double 7)

A lambda can take two inputs

This lambda takes two inputs, x and y. It multiplies the 3 and the 5 it is applied to.

main :: IO ()
main = print ((\x y -> x * y) 3 5)

Example

triple = \x -> x * 3

main :: IO ()
main = print [triple 2, triple 5, (\x -> x + 10) 1]

Key points

  • Lambda: a function with no name, written where it is needed.
  • Backslash: a lambda starts with a backslash, followed by its inputs.
  • Arrow: the -> symbol separates the inputs from the result, as in \x -> x * 2.
  • Stored lambda: a binding can hold a lambda, so the binding name works like a function name.
  • Several inputs: a lambda can take several inputs, as in \x y -> x + y.

In this example, the binding triple holds a lambda that multiplies its input by 3. The list applies triple to 2 and to 5, and applies a second lambda that adds 10 to 1, so the printed list shows 6, 15 and 11.

Note

a lambda is a plain value, so it can be stored or applied like any other function value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is the value of (\x -> x + 3) 5?