Professional Documents
Culture Documents
Programming in Haskell: Chapter 6 - Recursive Functions
Programming in Haskell: Chapter 6 - Recursive Functions
Programming in Haskell: Chapter 6 - Recursive Functions
1
Introduction
For example:
fac 4
=
product [1..4]
=
product [1,2,3,4]
=
1*2*3*4
=
24
3
Recursive Functions
fac 0 = 1
fac n = n * fac (n-1)
fac 3
=
3 * fac 2
=
3 * (2 * fac 1)
=
3 * (2 * (1 * fac 0))
=
3 * (2 * (1 * 1))
=
3 * (2 * 1)
=
3*2
=
6
5
Note:
6
Why is Recursion Useful?
7
Recursion on Lists
product [2,3,4]
=
2 * product [3,4]
=
2 * (3 * product [4])
=
2 * (3 * (4 * product []))
=
2 * (3 * (4 * 1))
=
24
9
Using the same pattern of recursion as in product
we can define the length function on lists.
length [1,2,3]
=
1 + length [2,3]
=
1 + (1 + length [3])
=
1 + (1 + (1 + length []))
=
1 + (1 + (1 + 0))
=
3
11
Using a similar pattern of recursion we can define
the reverse function on lists.
reverse [1,2,3]
=
reverse [2,3] ++ [1]
=
(reverse [3] ++ [2]) ++ [1]
=
((reverse [] ++ [3]) ++ [2]) ++ [1]
=
(([] ++ [3]) ++ [2]) ++ [1]
=
[3,2,1]
13
Multiple Arguments
14
Remove the first n elements from a list:
16
Using recursion, this specification can be translated
directly into an implementation:
Note:
q [3,2,4,1,5]
[1] [] [] [5]
18
Exercises
20
(2) Define a recursive function
[1,2,3,4,5,6]
21
(3) Define a recursive function