Haskell Higher-Order Functions
In Haskell, functions are values. You can pass them as arguments, return them from other functions and store them in lists. A function that takes or returns a function is called a higher-order function, and these are the main tool for replacing loops.
Functions as arguments
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
addVat :: Double -> Double
addVat price = price * 1.2
shout :: String -> String
shout s = s ++ "!"
main :: IO ()
main = do
print (applyTwice (+ 3) 10)
print (applyTwice addVat 100)
putStrLn (applyTwice shout "Hey")
print (applyTwice tail [1, 2, 3, 4])16
144.0
Hey!!
[3,4]
The type (a -> a) -> a -> a has parentheses around the first argument: it is one argument that is itself a function from a to a.
map: transform every element
map :: (a -> b) -> [a] -> [b] applies a function to every element and returns the list of results:
import Data.Char (toUpper)
celsiusToF :: Double -> Double
celsiusToF c = c * 9 / 5 + 32
main :: IO ()
main = do
print (map celsiusToF [0, 37, 100])
print (map length ["one", "three", "five"])
print (map (map toUpper) ["ab", "cd"]) -- map inside map
print (map fst [(1, 'x'), (2, 'y')])[32.0,98.6,212.0]
[3,5,4]
["AB","CD"]
[1,2]
filter: keep what matches
filter :: (a -> Bool) -> [a] -> [a] keeps the elements for which the predicate returns True:
isVowel :: Char -> Bool
isVowel c = c `elem` "aeiou"
main :: IO ()
main = do
print (filter even [1 .. 15])
print (filter isVowel "higher order functions")
print (filter (not . null) ["a", "", "b", ""])
print (length (filter (> 100) [42, 150, 99, 300, 101]))[2,4,6,8,10,12,14]
"ieoeuio"
["a","b"]
3
not . null combines two functions: "not empty". The dot is function composition, covered in its own lesson.
More higher-order helpers
| Function | Type (simplified) | What it does |
|---|---|---|
zipWith |
(a -> b -> c) -> [a] -> [b] -> [c] |
Combine two lists element by element |
takeWhile |
(a -> Bool) -> [a] -> [a] |
Take elements while the predicate holds |
dropWhile |
(a -> Bool) -> [a] -> [a] |
Drop elements while the predicate holds |
all, any |
(a -> Bool) -> [a] -> Bool |
Does every / some element satisfy it? |
iterate |
(a -> a) -> a -> [a] |
[x, f x, f (f x), …], infinitely |
until |
(a -> Bool) -> (a -> a) -> a -> a |
Apply f until the condition holds |
concatMap |
(a -> [b]) -> [a] -> [b] |
Map, then concatenate the results |
main :: IO ()
main = do
print (zipWith (*) [1, 2, 3] [10, 20, 30])
print (zipWith3 (\a b c -> a + b + c) [1, 2] [3, 4] [5, 6])
print (takeWhile (< 10) [1, 4, 9, 16, 25, 4])
print (dropWhile (== ' ') " indented")
print (all even [2, 4, 6], any (> 5) [1, 2, 3])
print (take 5 (iterate (* 2) 1))
print (until (> 1000) (* 3) 1)
print (concatMap (replicate 2) "abc")[10,40,90]
[9,12]
[1,4,9]
"indented"
(True,False)
[1,2,4,8,16]
2187
"aabbcc"
The \a b c -> … is an anonymous function, a lambda; see the next lesson.
Functions that return functions
A function can build and return a new function. Here discount takes a percentage and returns a pricing function:
discount :: Double -> (Double -> Double)
discount percent = \price -> price * (1 - percent / 100)
pricingRules :: [(String, Double -> Double)]
pricingRules =
[ ("regular", id)
, ("member", discount 10)
, ("staff", discount 30)
]
main :: IO ()
main = do
let blackFriday = discount 50
print (blackFriday 80)
mapM_ (\(name, rule) -> putStrLn (name ++ ": " ++ show (rule 200))) pricingRules40.0
regular: 200.0
member: 180.0
staff: 140.0
pricingRules is a list of functions. id is the identity function: it returns its argument unchanged.
Sorting with a key: sortOn and sortBy
Sorting is another place where passing a function shines. sortOn sorts by a key you compute from each element; sortBy takes a comparison function:
import Data.List (sortOn, sortBy)
import Data.Ord (comparing, Down (..))
main :: IO ()
main = do
let books = [("Dune", 1965, 412), ("Neuromancer", 1984, 271), ("Hyperion", 1989, 482)]
title (t, _, _) = t
year (_, y, _) = y
pages (_, _, p) = p
print (map title (sortOn pages books))
print (map title (sortOn (Down . year) books))
print (map title (sortBy (comparing title) books))["Neuromancer","Dune","Hyperion"]
["Hyperion","Neuromancer","Dune"]
["Dune","Hyperion","Neuromancer"]
Down from Data.Ord reverses the order, so sortOn (Down . year) sorts newest first.
Tip: When you catch yourself writing a recursive function over a list, ask first whether it is a
map, afilter, azipWithor a fold. Usually it is, and the library version is shorter and clearer.
Test yourself
What is map (* 2) (filter odd [1 .. 6])?
[2,4,6,8,10,12][2,6,10][1,3,5][4,8,12]
What does the type (a -> a) -> a -> a say about the first argument?
- It is a value of type
a - It is a function from
atoa - It is a pair
- The function takes three arguments
What is takeWhile (/= ' ') "hello world"?
"hello""world"" world""hello world"