In tro duction to F unctional Programming: Lecture 4 1 In - - PDF document

in tro duction to f unctional programming lecture 4 1 in
SMART_READER_LITE
LIVE PREVIEW

In tro duction to F unctional Programming: Lecture 4 1 In - - PDF document

In tro duction to F unctional Programming: Lecture 4 1 In tro duction to F unctional Programming John Harrison Univ ersit y of Cam bridge Lecture 4 Recursiv e functions and recursiv e t yp es T opics co v


slide-1
SLIDE 1 In tro duction to F unctional Programming: Lecture 4 1 In tro duction to F unctional Programming John Harrison Univ ersit y
  • f
Cam bridge Lecture 4 Recursiv e functions and recursiv e t yp es T
  • pics
co v ered:
  • Kinds
  • f
recursion
  • Num
b ers as a recursiv e t yp e
  • New
t yp es in ML
  • P
attern matc hing
  • More
examples: sums, lists and trees. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-2
SLIDE 2 In tro duction to F unctional Programming: Lecture 4 2 Recursiv e functions: factorial Recursiv e functions are cen tral to functional programming, so it's as w ell to b e clear ab
  • ut
them. Roughly sp eaking, a recursiv e function is
  • ne
`dened in terms
  • f
itself '. F
  • r
example, w e can dene the factorial function in mathematics as n! = 8 < : 1 if n = n
  • (n
  • 1)!
  • therwise
This translates directly in to ML:
  • fun
fact n = if n = then 1 else n * fact(n
  • 1);
> val fact = fn : int
  • >
int
  • fact
6; > val it = 720 : int John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-3
SLIDE 3 In tro duction to F unctional Programming: Lecture 4 3 Recursiv e functions: Fib
  • nacci
Another classic example
  • f
a function dened recursiv ely is the n th mem b er
  • f
the Fib
  • nacci
sequence 1; 1; 2; 3; 5; 8; 13; 21; : : : where eac h n um b er is the sum
  • f
the t w
  • previous
  • nes.
f ib n = 8 > > < > > : 1 if n = 1 if n = 1 f ib n2 + f ib n1
  • therwise
Once again the ML is similar:
  • fun
fib n = if n = then 1 else if n = 1 then 1 else fib(n
  • 2)
+ fib(n
  • 1);
> val fib = fn : int
  • >
int
  • fib
5; > val it = 8 : int
  • fib
6; > val it = 13 : int John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-4
SLIDE 4 In tro duction to F unctional Programming: Lecture 4 4 Kinds
  • f
recursion Ho w do w e kno w that the ev aluation
  • f
these functions will terminate? T rivially fact terminates, since it do esn't generate a recursiv e call. If w e ev aluate fact n for n > 0, w e need fact (n
  • 1),
then ma yb e fact (n
  • 2),
fact (n
  • 3)
etc., but ev en tually , after n recursiv e calls, w e reac h the base case. This is wh y termination is guaran teed. (Though it lo
  • ps
for n < 0.) This sort
  • f
recursion, where the argumen t to the recursiv e call(s) decreases b y 1 eac h time is called primitive recursion. The function fib is dieren t: the recursion is not primitiv e. T
  • kno
w that fib n terminates, w e need to kno w that fib (n
  • 1)
and fib (n
  • 2)
terminate. Nev ertheless, w e are still sure to reac h a base case ev en tually b ecause the argumen t do es b ecome smaller, and can't skip
  • v
er b
  • th
1 and 0. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-5
SLIDE 5 In tro duction to F unctional Programming: Lecture 4 5 Pro
  • fs
  • f
termination More formally , w e can turn the ab
  • v
e in to a pr
  • f
b y mathematical induction than fact n terminates for eac h natural n um b er n. W e pro v e that fact terminates, then that if fact n terminates, so do es fact (n + 1). 8P : P (0) ^ (8n: P (n) ) P (n + 1)) ) 8n: P (n) The appropriate w a y to pro v e fib n terminates for all natural n um b ers n is to use the principle
  • f
wel lfounde d induction, rather than step-b y-step induction. 8P : (8n: (8m: m < n ) P (m)) ) P (n) ) 8n: P (n) There is th us a close parallel b et w een the kind
  • f
r e cursion used to dene a function and the kind
  • f
induction used to reason ab
  • ut
it, in this case sho w that it terminates. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-6
SLIDE 6 In tro duction to F unctional Programming: Lecture 4 6 The naturals as a recursiv e t yp e The principle
  • f
mathematical induction sa ys exactly that ev ery natural n um b er is generated b y starting with and rep eatedly adding
  • ne,
i.e. applying the successor
  • p
eration S (n) = n + 1. If w e regard the natural n um b ers as a set
  • r
a t yp e, then w e ma y sa y that it is generated b y the c
  • nstructors
and S . Moreo v er, eac h natural n um b er can
  • nly
b e generated in
  • ne
w a y lik e this: w e can't ha v e S (n) = 0, and if p times z }| { S (S (
  • (S
(0))
  • ))
= q times z }| { S (S (
  • (S
(0))
  • ))
then p = q . The second prop ert y is equiv alen t to sa ying that S is inje ctive. In suc h cases the set
  • r
t yp e is said to b e fr e e, b ecause there are no relationships forced
  • n
the elemen ts. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-7
SLIDE 7 In tro duction to F unctional Programming: Lecture 4 7 New t yp es in ML ML allo ws us to dene new t yp es in just this w a y . W e write:
  • datatype
num = O | S
  • f
num; > datatype num con O = O : num con S = fn : num
  • >
num This declares a completely new t yp e called num and the appropriate new constructors. But in
  • rder
to dene functions lik e fact w e need to b e able to tak e n um b ers apart again, i.e. go from S(n) to n. W e ha v en't got something lik e subtraction here. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-8
SLIDE 8 In tro duction to F unctional Programming: Lecture 4 8 Prop erties
  • f
t yp e constructors All t yp e constructors arising from a datatype denition ha v e three k ey prop erties, whic h w e can illustrate using the ab
  • v
e example. 1. They are exhaustiv e, . ev ery elemen t
  • f
the new t yp e is
  • btainable
either b y O
  • r
as S x for some x. 2. They are injectiv e, i.e. an equalit y test S x = S y is true if and
  • nly
if x = y. 3. They are distinct, i.e. their ranges are disjoin t. More concretely this means in the ab
  • v
e example that S(x) = O is false whatev er x migh t b e. Because
  • f
these prop erties, w e can dene functions, including recursiv e
  • nes,
b y p attern matching. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-9
SLIDE 9 In tro duction to F unctional Programming: Lecture 4 9 P attern matc hing | ho w W e p erform pattern matc hing b y using more general expressions called varstructs as the argumen ts in fn => ...
  • r
fun => ... expressions. Moreo v er, w e can ha v e sev eral dieren t cases to matc h against, separated b y |. F
  • r
example, here is a test for whether something
  • f
t yp e num is zero:
  • fun
iszero O = true | iszero (S n) = false; > val iszero = fn : num
  • >
bool
  • iszero
(S(S(O))); > val it = false : bool
  • iszero
O; > val it = true : bool This function has the prop ert y , naturally enough, that when applied to O it returns true and when applied to S x it returns false. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-10
SLIDE 10 In tro duction to F unctional Programming: Lecture 4 10 P attern matc hing | wh y Wh y is this v alid? 1. The constructors are distinct, so w e kno w that there is no am biguit y . The cases for O and S x don't
  • v
erlap. 2. The constructors are injectiv e, so w e can alw a ys reco v er x from S x if w e w an t to use x in the b
  • dy
  • f
that clause. 3. The constructors are exhaustive, so w e kno w that if w e ha v e a case for eac h constructor, the function is dened ev erywhere
  • n
the t yp e. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-11
SLIDE 11 In tro duction to F unctional Programming: Lecture 4 11 Non-exhaustiv e matc hing In fact, w e can dene partial functions that don't co v er ev ery case. Here is a `predecessor' function.
  • fun
pred (S(n)) = n; ! Toplevel input: ! fun pred (S(n)) = n; ! ^^^^^^^^^^^^^^^ ! Warning: pattern matching is not exhaustive > val pred = fn : num
  • >
num The compiler w arns us
  • f
this fact. If w e try to use the function
  • n
an argumen t not
  • f
the form S x, then it will not w
  • rk:
  • pred
O; ! Uncaught exception: ! Match John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-12
SLIDE 12 In tro duction to F unctional Programming: Lecture 4 12 General matc hing Moreo v er, w e can p erform matc hing ev en in
  • ther
situations, when the matc hes migh t not b e m utually exclusiv e. In this case, the rst p
  • ssible
matc h is tak en.
  • (fn
true => 1 | false => 0) (4 < 3); > val it = : int
  • (fn
true => 1 | false => 0) (2 < 4); > val it = 1 : int Ho w ev er, in general, constan ts need sp ecial constructor status,
  • r
they will b e treated just as v ariables for binding:
  • let
val t = true and f = false in (fn t => 1 | f => 0) (4 < 3) end; ! ..... > val it = 1 : int John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-13
SLIDE 13 In tro duction to F unctional Programming: Lecture 4 13 Nonrecursiv e t yp es New t yp es don't actually need to b e recursiv e. F
  • r
example, here is a t yp e
  • f
disjoin t sums.
  • datatype
('a,'b)sum = inl
  • f
'a | inr
  • f
'b; > datatype ('a, 'b) sum con inl = fn : 'a
  • >
('a, 'b) sum con inr = fn : 'b
  • >
('a, 'b) sum This creates a new t yp e c
  • nstructor
sum and t w
  • new
constructors. Again w e can dene functions b y pattern matc hing, e.g.
  • fun
  • utl
(inl a) = a; ! Toplevel input: ! fun
  • utl
(inl a) = a; ! ^^^^^^^^^^^^^^^^ ! Warning: pattern matching is not exhaustive > val
  • utl
= fn : ('a, 'b) sum
  • >
'a John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-14
SLIDE 14 In tro duction to F unctional Programming: Lecture 4 14 Lists (1) An imp
  • rtan
t t yp e is the t yp e
  • f
nite lists:
  • datatype
('a)list = Nil | Cons
  • f
'a * ('a)list; > datatype 'a list con Nil = Nil : 'a list con Cons = fn : 'a * 'a list
  • >
'a list W e imagine Nil as the empt y list and Cons as a function that adds a new elemen t
  • n
the fron t
  • f
a list. The lists [], [1], [1; 2] and [1; 2; 3] are written: Nil; Cons(1,Nil); Cons(1,Cons(2,Nil )); Cons(1,Cons(2,Con s(3 ,N il) )) ; John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-15
SLIDE 15 In tro duction to F unctional Programming: Lecture 4 15 Lists (2) Actually , this t yp e is already built in. The empt y list is written [] and the recursiv e constructor ::, has inx status. (Y
  • u
can mak e y
  • ur
  • wn
iden tier f inx b y writing infixr f.) Th us, the ab
  • v
e lists are actually written:
  • [];
> val it = [] : 'a list
  • 1::[];
> val it = [1] : int list
  • 1::2::[];
> val it = [1, 2] : int list
  • 1::2::3::[];
> val it = [1, 2, 3] : int list The v ersion that is prin ted can also b e used for input:
  • [1,2,3,4,5]
= 1::2::3::4::5::[ ]; > val it = true : bool John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-16
SLIDE 16 In tro duction to F unctional Programming: Lecture 4 16 P attern matc hing
  • v
er lists W e can no w dene functions b y pattern matc hing in the usual w a y . F
  • r
example, w e can dene functions to tak e the head and tail
  • f
a list:
  • fun
hd (h::t) = h; ! Toplevel input: ! fun hd (h::t) = h; ! ^^^^^^^^^^^^^ ! Warning: pattern matching is not exhaustive > val hd = fn : 'a list
  • >
'a
  • fun
tl (h::t) = t; ! Toplevel input: ! fun tl (h::t) = t; ! ^^^^^^^^^^^^^ ! Warning: pattern matching is not exhaustive > val tl = fn : 'a list
  • >
'a list ML w arns us that they will fail when applied to an empt y list. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-17
SLIDE 17 In tro duction to F unctional Programming: Lecture 4 17 Recursiv e functions
  • v
er lists It is p
  • ssible
to mix pattern matc hing and recursion. This is natural since the t yp e itself is dened recursiv ely . F
  • r
example, here is a function to return the length
  • f
a list:
  • fun
length [] = | length (h::t) = 1 + length t; > val length = fn : 'a list
  • >
int
  • length
[5,3,1]; > val it = 3 : int Alternativ ely , this can b e written in terms
  • f
  • ur
earlier `destructor' functions hd and tl. This st yle
  • f
function denition is more usual in man y languages, notably LISP , but the direct use
  • f
pattern matc hing is
  • ften
more elegan t. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-18
SLIDE 18 In tro duction to F unctional Programming: Lecture 4 18 T rees Lists can b e though
  • f
as tree structures, but are rather `one-sided'. Here is a t yp e
  • f
binary trees with in tegers at the branc h no des:
  • datatype
tree = Leaf | Br
  • f
(tree*int*tree); > datatype tree con Leaf = Leaf : tree con Br = fn : tree * int * tree
  • >
tree F
  • r
example, the follo wing recursiv e function adds up all the in tegers in a tree:
  • fun
treesum Leaf = | treesum (Br(t1,n,t2)) = treesum t1 + n + treesum t2; > val treesum = fn : tree
  • >
int Suc h tree structures are
  • ften
useful for represen ting the syn tax
  • f
formal languages, e.g. arithmetic expressions, C programs. John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998
slide-19
SLIDE 19 In tro duction to F unctional Programming: Lecture 4 19 The subtlet y
  • f
recursiv e t yp es Consider the follo wing:
  • datatype
('a)embedding = K
  • f
('a)embedding->'a ; This lo
  • ks
suspicious b ecause it em b eds the function space A ! B inside A. In fact it
  • nly
em b eds the c
  • mputable
functions. It allo ws us to dene recursiv e functions without explicit use
  • f
recursion:
  • fun
Y h = let fun g (K x) z = h (x (K x)) z in g (K g) end;
  • val
fact = Y (fn f => fn n => if n = then 1 else n * f(n
  • 1));
> val fact = fn : int
  • >
int
  • fact
6; > val it = 720 : int John Harrison Univ ersit y
  • f
Cam bridge, 22 Jan uary 1998