In this appendix we present model solutions to selected exercises for each chapter. If solutions are being tested out using GHCi, note that some functions may need to be renamed to avoid clashing with built-in functions from the standard prelude. For example, product could be renamed to myproduct.
Introduction
Exercise 1
double (double 2)
= { applying the inner double }
double (2 + 2)
= { applying double }
(2 + 2) + (2 + 2)
= { applying the first + }
4 + (2 + 2)
= { applying the second + }
4 + 4
= { applying + }
8
or
double (double 2)
= { applying the outer double }
(double 2) + (double 2)
= { applying the second double }
(double 2) + (2 + 2)
= { applying the second + }
(double 2) + 4
= { applying double }
(2 + 2) + 4
= { applying the first + }
4 + 4
= { applying + }
8
There are a number of other possible answers.
Exercise 2
sum [x]
= { applying sum }
x + sum []
= { applying sum }
x + 0
= { applying + }
x
Exercise 3
product [] = 1
product (n:ns) = n * product ns
For example:
product [2,3,4]
= { applying product }
2 * (product [3,4])
= { applying product }
2 * (3 * product [4])
= { applying product }
2 * (3 * (4 * product []))
= { applying product }
2 * (3 * (4 * 1))
= { applying * }
24
First steps
Exercise 2
(2^3)*4
(2*3)+(4*5)
2+(3*(4^5))
Exercise 3
n = a ‘div‘ length xs
where
a = 10
xs = [1,2,3,4,5]
Exercise 4
last xs = head (reverse xs)
or
last xs = xs!! (length xs - 1)
Types and classes
Exercise 1
[’a’,’b’,’c’] :: [Char]
(’a’,’b’,’c’) :: (Char,Char,Char)
[(False,’O’),(True,’1’)] :: [(Bool,Char)]
([False,True],[’0’,’1’]) :: ([Bool],[Char])
[tail, init, reverse] :: [[a] -> [a]]
Exercise 2
bools = [False,True]
nums = [[1,2],[3,4],[5,6]]
add x y z = x+y+z
copy x = (x,x)
apply f x = f x
There are a number of other possible answers for bools, nums and add.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.