Lambdas
The last spanner we need in our functional programming toolbox is λ (lambda). Lambda expressions are anonymous functions. Consider a situation where you need a function only once, for example in an expression like
let big x = x>7 in filter big [1,10,100]
A lambda expression allows us to write this directly, without defining a name (big
) for the helper function:
filter (\x -> x>7) [1,10,100]
Here are some more examples in GHCi:
Prelude> (\x -> x*x) 3
9
Prelude> (\x -> reverse x == x) "ABBA"
True
Prelude> filter (\x -> reverse x == x) ["ABBA","ACDC","otto","lothar","anna"]
["ABBA","otto","anna"]
Prelude> (\x y -> x^2+y^2) 2 3 -- multiple arguments
13
The Haskell syntax for lambdas is a bit surprising. The backslash character (\
) stands for the greek letter lambda (λ). The Haskell expression \x -> x+1
is trying to mimic the mathematical notation λx. x+1. Other languages use syntax like x => x+1
(JavaScript) or lambda x: x+1
(Python).
Note! You never need to use a lambda expression. You can always instead define the function normally using let
or where
.
By the way, lambda expressions are quite powerful constructs which have a deep theory of their own, known as Lambda calculus. Some even consider purely functional programming languages such as Haskell to be typed extensions of Lambda calculus with extra syntax.
You can check your current points from the blue blob in the bottom-right corner of the page.