Haskell Lambdas & Currying
This lesson covers three closely related ideas: lambdas (functions without a name), currying (every function takes exactly one argument) and partial application (calling a function with fewer arguments than it expects to get a new function). Together they explain why Haskell function types are written with all those arrows.
Lambdas
A lambda is written with a backslash (it looks a little like the Greek λ), the parameters, an arrow and the body:
main :: IO ()
main = do
print ((\x -> x * x + 1) 5)
print (map (\x -> x * x + 1) [1, 2, 3])
print (filter (\w -> length w > 3) ["a", "tree", "is", "green"])
print (zipWith (\name age -> name ++ "=" ++ show age) ["Ana", "Ben"] [31, 27])
print (map (\(a, b) -> a * b) [(2, 3), (4, 5)]) -- a pattern as the parameter26
[2,5,10]
["tree","green"]
["Ana=31","Ben=27"]
[6,20]
Lambdas are ideal for small, one-off functions passed to map, filter or zipWith. If the body grows past one line, or you need the same function twice, give it a name with where instead.
Currying: one argument at a time
Look at this type again:
add :: Int -> Int -> IntThe arrow -> associates to the right, so this really means Int -> (Int -> Int): add takes one Int and returns a function that takes the second Int. Calling add 2 3 is really (add 2) 3. This is called currying, after Haskell Curry. These three definitions are the same function:
add1 :: Int -> Int -> Int
add1 x y = x + y
add2 :: Int -> Int -> Int
add2 x = \y -> x + y
add3 :: Int -> Int -> Int
add3 = \x -> \y -> x + y
main :: IO ()
main = do
print (add1 2 3, add2 2 3, add3 2 3)
let addTen = add1 10 -- give only the first argument
print (addTen 5)
print (map addTen [1, 2, 3])(5,5,5)
15
[11,12,13]
Partial application
Because of currying, giving a function fewer arguments than it expects is not an error: you get back a function waiting for the rest. This is partial application, and it removes a lot of boilerplate:
formatPrice :: String -> Int -> Double -> String
formatPrice currency decimals amount =
currency ++ show (fromIntegral (round (amount * 10 ^ decimals)) / 10 ^ decimals)
main :: IO ()
main = do
let inEuro = formatPrice "EUR " 2 -- String -> Int fixed, waits for the amount
inYen = formatPrice "JPY " 0
print (map inEuro [3.14159, 10])
print (map inYen [1999.6, 250])
print (map (replicate 3) "ab") -- replicate partially applied
print (map (take 2) ["hello", "world"])["EUR 3.14","EUR 10.0"]
["JPY 2000.0","JPY 250.0"]
["aaa","bbb"]
["he","wo"]
Tip: Because partial application fixes arguments from the left, Haskell libraries put the argument that changes least first (the configuration) and the data last. That is why it's
map f xs,filter p xsandtake n xs, never the other way around.
Operator sections
Operators can be partially applied too, with a section: wrap the operator and one operand in parentheses.
| Section | Means | Example |
|---|---|---|
(+ 1) |
\x -> x + 1 |
map (+ 1) [1, 2] is [2,3] |
(* 2) |
\x -> x * 2 |
|
(2 ^) |
\x -> 2 ^ x |
map (2 ^) [1, 2, 3] is [2,4,8] |
(^ 2) |
\x -> x ^ 2 |
map (^ 2) [1, 2, 3] is [1,4,9] |
(/ 2) vs (2 /) |
halve vs "two divided by" | the side matters for non-commutative operators |
(`div` 2) |
\x -> div x 2 |
backticked functions work too |
main :: IO ()
main = do
print (map (2 ^) [0 .. 5])
print (map (^ 2) [0 .. 5])
print (map (/ 4) [8, 2], map (4 /) [8, 2])
print (filter (`elem` "aeiou") "sectioning")
print (map (subtract 1) [10, 20])[1,2,4,8,16,32]
[0,1,4,9,16,25]
([2.0,0.5],[0.5,2.0])
"eioi"
[9,19]
One exception: (- 1) is the number minus one, not a section. Use subtract 1 (or \x -> x - 1) to subtract.
flip, curry and uncurry
Sometimes the arguments are in the wrong order or come bundled in a tuple. Three small Prelude functions adapt them:
main :: IO ()
main = do
print (flip (-) 1 10) -- 10 - 1
print (map (flip div 3) [9, 10, 11]) -- divide each by 3
print (uncurry (+) (4, 5)) -- a 2-argument function on a pair
print (map (uncurry max) [(1, 7), (9, 2)])
print (curry fst 'a' 'b') -- a pair function with 2 arguments9
[3,3,3]
9
[7,9]
'a'
| Function | Type |
|---|---|
flip |
(a -> b -> c) -> b -> a -> c |
uncurry |
(a -> b -> c) -> (a, b) -> c |
curry |
((a, b) -> c) -> a -> b -> c |
Point-free style
Partial application lets you drop a trailing argument that appears on both sides of a definition. sumAll xs = foldr (+) 0 xs can become sumAll = foldr (+) 0. This is called point-free style (the "points" are the arguments):
countLong :: [String] -> Int
countLong = length . filter ((> 4) . length)
doubleAll :: [Int] -> [Int]
doubleAll = map (* 2)
main :: IO ()
main = do
print (countLong ["tiny", "medium", "enormous", "a"])
print (doubleAll [5, 6, 7])2
[10,12,14]
Use it when it makes the code clearer. When you need to puzzle over a point-free definition, put the argument back.
Test yourself
What is the type of max 5, given max :: Ord a => a -> a -> a and 5 :: Int?
IntInt -> IntInt -> Int -> Int- A type error
What is map (10 -) [1, 2, 3]?
[-9,-8,-7][9,8,7][11,12,13]- A type error
Why is (- 1) not a section?
- It is a section
- It is parsed as the negative number -1
- Sections only work with
+ - Subtraction is not an operator