map, filter, zipWith and flip
Functions as values
A function is a value like any other: it can be an argument, a result, an element of a list or the value of a binding. The type writes it with an arrow, so (a -> a) -> a -> a is a function that takes a function and a value and returns a value.
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
applyTwice (+ 3) 1 -- 7
applyTwice reverse "ab" -- "ab"
The first line applies (+ 3) twice to 1 and gets 7. The second applies reverse twice and gets the original string back, which is the point of (a -> a): the function and the value it is applied to have the same type, so they can be chained any number of times.
map and filter
map applies a function to every element and keeps the shape of the list; filter keeps the elements for which a predicate is True and drops the rest. Together they replace most loops that build a list.
map (* 2) [1, 2, 3] -- [2,4,6]
filter even [1 .. 10] -- [2,4,6,8,10]
map show [1, 2] -- ["1","2"]
filter (> 2) [1, 2, 3, 4] -- [3,4]
Both are higher-order in the same way: the function is the first argument and the list the second. That order is what makes a partially applied version useful, map (* 2) is a function from a list of numbers to a list of numbers, and the next lesson takes that idea apart.
zipWith and flip
zipWith is map over two lists at once: it takes a two-argument function and combines the lists element by element, stopping at the shorter one. flip takes a two-argument function and swaps its arguments, which is how a function written for one order is reused in the other.
zipWith (+) [1, 2, 3] [10, 20, 30] -- [11,22,33]
zipWith (*) [1, 2] [3, 4, 5] -- [3,8]
flip (-) 3 10 -- 7
flip (++) "b" "a" -- "ab"
The third line is the one that needs reading twice: flip (-) 3 10 is 10 - 3, so it prints 7. Without flip the same expression is 3 - 10, which is -7. The fourth line is the same idea with strings, and it is why flip is worth knowing: it turns any two-argument function into its mirror image without a lambda.
any and all
any and all take a predicate and a list and answer a Bool. They are higher-order and lazy at the same time: any stops at the first True, all at the first False, so they work on an infinite list when the answer comes early.
any even [1, 3, 5] -- False
all even [2, 4, 6] -- True
any (> 100) [1 ..] -- True, and it stops at 101
all (< 5) [1, 2] -- True
The third line is the useful one: the list has no end and the function still answers, because it asks for elements one at a time until the predicate holds. That is the same short-circuit as &&, lifted to a list.
A program of its own
All of the above in one file, with two small functions built from them:
module Main (main) where
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
main :: IO ()
main = do
print (map (* 2) [1, 2, 3] :: [Int])
print (filter even [1 .. 10] :: [Int])
print (zipWith (+) [1, 2, 3] [10, 20, 30] :: [Int])
print (flip (-) 3 10 :: Int)
print (any even ([1, 3, 5] :: [Int]) :: Bool)
print (all even ([2, 4, 6] :: [Int]) :: Bool)
print (applyTwice (+ 3) 1 :: Int)
ghc -Wall -O1 -o hof hof.hs
./hof
[2,4,6]
[2,4,6,8,10]
[11,22,33]
7
False
True
7
The numbers are the ones the sections predicted. The two 7s are the same value from different paths: flip (-) 3 10 and applyTwice (+ 3) 1 both happen to be 7, and the coincidence is a good check that each line does what its prose says.
A second program, built the same way, shows the same functions over strings, where the element type is String and the function arguments are take 1 and max:
module Main (main) where
initials :: [String] -> String
initials = concatMap (take 1)
longest :: [String] -> Int
longest = foldr (max . length) 0
main :: IO ()
main = do
putStrLn (initials ["Ada", "Grace", "Alan"])
print (longest ["Ada", "Grace", "Alan"])
print (filter (not . null) ["", "x", ""] :: [String])
ghc -Wall -O1 -o names names.hs
./names
AGA
5
["x"]
concatMap is map followed by concat, which is how a function that returns a list per element becomes a function that returns one list. The middle line folds the lengths with max instead of calling maximum, because maximum is partial on an empty list; with a starting value of 0 the function answers for every input.
Exercises
- Write applyN :: Int -> (a -> a) -> a -> a with a recursion over the count.
- Use map and filter together to print the squares of the even numbers from 1 to 10.
- Predict zipWith (-) [10, 20] [1, 2] and then the same with flip.
- Explain why any (> 100) [1 ..] terminates and all (< 100) [1 ..] does not.
- Rewrite filter (not . null) without composition and compare the two.
- Use zipWith to join two lists of words with a dash between them.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
map (* 2) [1, 2, 3]produce?Answer
[2,4,6]
map applies the function to each element and keeps the length, so three elements double to 2, 4 and 6.
-
What does
filter even [1 .. 10]produce?Answer
[2,4,6,8,10]
filter keeps the elements whose predicate holds, which are the even numbers up to 10.
-
What does this program print?
module Main (main) where main :: IO () main = print (flip (-) 3 10 :: Int)Answer
7
flip swaps the arguments, so this is 10 - 3, which is 7.
-
What does
zipWith (+) [1, 2, 3] [10, 20, 30]produce?Answer
[11,22,33]
zipWith combines the lists element by element with the function given.
-
What happens when the two lists of zipWith have different lengths?
Answer
It stops at the shorter one
zipWith runs out of pairs when either list ends, so the result has the length of the shorter list.
-
What does
any even [1, 3, 5]return?Answer
False
None of the three odd numbers is even, so any finds no element that satisfies the predicate.
-
Why does
any (> 100) [1 ..]terminate?Answer
any stops at the first element that satisfies the predicate
The list is unbounded, but any asks for elements one at a time and stops at 101.
-
What does
applyTwice (+ 3) 1print?Answer
7
The function adds 3 twice to 1, giving 7.
-
What does this program print?
module Main (main) where initials :: [String] -> String initials = concatMap (take 1) main :: IO () main = putStrLn (initials ["Ada", "Grace", "Alan"])Answer
AGA
take 1 gives one character per name and concatMap joins the three strings.
-
What is the type of
map?Answer
(a -> b) -> [a] -> [b]map takes the function first and the list second, and the result has the type the function returns.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev