Programming in Haskell: Chapter 7 - Higher-Order Functions
Programming in Haskell: Chapter 7 - Higher-Order Functions
Programming in Haskell: Chapter 7 - Higher-Order Functions
1
Introduction
twice :: (a a) a a
twice f x = f (f x)
3
The Map Function
For example:
[2,4,6,8]
4
The map function can be defined in a particularly
simple manner using a list comprehension:
map f xs = [f x | x xs]
map f [] = []
map f (x:xs) = f x : map f xs
5
The Filter Function
For example:
[2,4,6,8,10]
6
Filter can be defined using a list comprehension:
filter p xs = [x | x xs, p x]
filter p [] = []
filter p (x:xs)
|px = x : filter p xs
| otherwise = filter p xs
7
The Foldr Function
f [] = v
f (x:xs) = x f xs
sum [] = 0
=0
v
product [] = 1
v=1
product (x:xs) = x * product xs =
*
v=
and [] = True
and (x:xs) = x && and xs
True
= &&
9
The higher-order library function foldr (fold right)
encapsulates this simple pattern of recursion, with
the function and the value v as arguments.
For example:
foldr :: (a b b) b [a] b
foldr f v [] =v
foldr f v (x:xs) = f x (foldr f v xs)
11
For example:
sum [1,2,3]
=
foldr (+) 0 [1,2,3]
=
foldr (+) 0 (1:(2:(3:[])))
=
1+(2+(3+0))
=
6
Replace each (:)
by (+) and [] by 0.
12
For example:
product [1,2,3]
=
foldr (*) 1 [1,2,3]
=
foldr (*) 1 (1:(2:(3:[])))
=
1*(2*(3*1))
=
6
Replace each (:)
by (*) and [] by 1.
13
Other Foldr Examples
14
For example:
length [1,2,3]
=
length (1:(2:(3:[])))
=
1+(1+(1+0))
=
3 Replace each (:)
by _ n 1+n
Hence, we have: and [] by 0.
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
For example:
Replace each (:) by
x xs xs ++ [x]
reverse [1,2,3] and [] by [].
=
reverse (1:(2:(3:[])))
=
(([] ++ [3]) ++ [2]) ++ [1]
=
[3,2,1]
16
Hence, we have:
Replace each
(++ ys) = foldr (:) ys
(:) by (:) and
[] by ys.
17
Why Is Foldr Useful?
18
Other Library Functions
(.) :: (b c) (a b) (a c)
f . g = x f (g x)
For example:
For example:
True
20
Dually, the library function any decides if at least
one element of a list satisfies a predicate.
For example:
True
21
The library function takeWhile selects elements from
a list while a predicate holds of all the elements.
For example:
"abc"
22
Dually, the function dropWhile removes elements
while a predicate holds of all the elements.
For example:
"abc"
23
Exercises
24