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

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

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

In tro duction to F unctional Programming: Lecture 6 1 In tro duction to F unctional Programming John Harrison Univ ersit y of Cam bridge Lecture 6 Eectiv e ML T opics co v ered: Using standard com


slide-1
SLIDE 1 In tro duction to F unctional Programming: Lecture 6 1 In tro duction to F unctional Programming John Harrison Univ ersit y
  • f
Cam bridge Lecture 6 Eectiv e ML T
  • pics
co v ered:
  • Using
standard com binators
  • Abstract
t yp es
  • T
ail recursion and accum ulators
  • F
  • rcing
ev aluation
  • Minimizing
consing John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-2
SLIDE 2 In tro duction to F unctional Programming: Lecture 6 2 Using standard com binators It
  • ften
turns
  • ut
that a few c
  • mbinators
are v ery useful: w e can implemen t practically an ything b y plugging them together, esp ecially giv en higher
  • rder
functions. F
  • r
example, the itlist function: itlist f [x 1 ; x 2 ; : : : ; x n ] b = f x 1 (f x 2 (f x 3 (
  • (f
x n b)))) can
  • ften
b e used to a v
  • id
explicit recursiv e denitions
  • v
er lists. W e dene it as:
  • fun
itlist f [] b = b | itlist f (h::t) b = f h (itlist f t b); > val itlist = fn : ('a
  • >
('b
  • >
'b))
  • >
'a list
  • >
'b
  • >
'b F unctions
  • f
this sort are
  • ften
built in to functional langauges, and sometimes called something lik e fold. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-3
SLIDE 3 In tro duction to F unctional Programming: Lecture 6 3 Itlist examples (1) F
  • r
example, here is a function to add up all the elemen ts
  • f
a list:
  • fun
sum l = itlist (fn x => fn sum => x + sum) l 0; > val sum = fn : int list
  • >
int
  • sum
[1,2,3,4,5]; > val it = 15 : int
  • sum
[]; > val it = : int If w e w an t to m ultiply the elemen ts instead, w e c hange it to:
  • fun
prod l = itlist (fn x => fn prod => x * prod) l 1; > val prod = fn : int list
  • >
int
  • prod
[1,2,3,4,5]; > val it = 120 : int John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-4
SLIDE 4 In tro duction to F unctional Programming: Lecture 6 4 Itlist examples (2) Here is a ltering function:
  • fun
filter p l = itlist (fn x => fn s => if p x then x::s else s) l []; and here are some logical
  • p
erations
  • v
er lists:
  • fun
forall p l = itlist (fn h => fn a => p(h) andalso a) l true;
  • fun
exists p l = itlist (fn h => fn a => p(h)
  • relse
a) l false; and some
  • ld
fa v
  • urites:
  • fun
length l = itlist (fn x => fn s => s + 1) l 1;
  • fun
append l m = itlist (fn h => fn t => h::t) l m;
  • fun
map f l = itlist (fn x => fn s => (f x)::s) l []; John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-5
SLIDE 5 In tro duction to F unctional Programming: Lecture 6 5 Itlist examples (3) W e can implemen t set
  • p
erations quite directly using these com binators as building blo c ks.
  • fun
mem x l = exists (fn y => y = x) l;
  • fun
insert x l = if mem x l then l else x::l;
  • fun
union l1 l2 = itlist insert l1 l2;
  • fun
setify l = union l [];
  • fun
Union l = itlist union l [];
  • fun
intersect l1 l2 = filter (fn x => mem x l2) l1;
  • fun
subtract l1 l2 = filter (fn x => not (mem x l2)) l1;
  • fun
subset l1 l2 = forall (fn t => mem t l2) l1; John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-6
SLIDE 6 In tro duction to F unctional Programming: Lecture 6 6 Abstract t yp es An abstract t yp e starts with an
  • rdinary
recursiv e t yp e, and then imp
  • ses
restrictions
  • n
ho w the
  • b
jects
  • f
the t yp e can b e manipulated. Essen tially , users can
  • nly
in teract b y a particular `in terface'
  • f
functions and v alues. The adv an tage is that users c annot rely
  • n
an y
  • ther
in ternal details
  • f
the t yp e. This impro v es mo dularit y , e.g. it is easy to replace the implemen tation
  • f
the abstract t yp e with a new `b etter' (smaller, faster, not paten ted . . . )
  • ne,
without requiring an y c hanges to user co de. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-7
SLIDE 7 In tro duction to F unctional Programming: Lecture 6 7 Example: sets (1) Here is an abstract t yp e for in teger sets.
  • abstype
set = Set
  • f
int list with val empty = Set [] fun set_insert a (Set s) = Set (insert a s) fun set_union (Set s) (Set t) = Set (union s t) fun set_intersect (Set s) (Set t) = Set (intersect s t) fun set_subset (Set s) (Set t) = subset s t end; Users can't access the in ternal represen tation (lists), whic h is
  • nly
done via the in terface functions. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-8
SLIDE 8 In tro duction to F unctional Programming: Lecture 6 8 Example: sets (2) Man y
  • f
the
  • p
erations are m uc h more ecien t if w e k eep the lists sorted in to n umerical
  • rder.
F
  • r
example:
  • fun
sunion [] [] = [] | sunion [] l = l | sunion l [] = l | sunion (h1::t1) (h2::t2) = if h1 < h2 then h1::(sunion t1 (h2::t2)) else if h1 > h2 then h2::(sunion (h1::t1) t2) else h1::(sunion t1 t2); > val sunion = fn : int list
  • >
int list
  • >
int list W e can c hange the in ternal represen tation to use sorted lists (or balanced trees,
  • r
arra ys, . . . ) and no c hanges are needed to co de using the abstract t yp e. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-9
SLIDE 9 In tro duction to F unctional Programming: Lecture 6 9 Storing lo cal v ariables Recall
  • ur
denition
  • f
the factorial: #fun fact n = if n = then 1 else n * fact(n
  • 1);
A call to fact 6 causes another call to fact 5 (and b ey
  • nd),
but the computer needs to sa v e the
  • ld
v alue 6 in
  • rder
to do the nal m ultiplication. Therefore, the lo cal v ariables
  • f
a function, in this case n, cannot b e stored in a xed place, b ecause eac h instance
  • f
the function needs its
  • wn
cop y . Instead eac h instance
  • f
the function is allo cated a frame
  • n
a stack. This tec hnique is similar in ML to most
  • ther
languages that supp
  • rt
recursion, including C. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-10
SLIDE 10 In tro duction to F unctional Programming: Lecture 6 10 The stac k Here is an imaginary snapshot
  • f
the stac k during the ev aluation
  • f
the innermost call
  • f
fact: SP
  • n
= n = 1 n = 2 n = 3 n = 4 n = 5 n = 6 Note that w e use ab
  • ut
n w
  • rds
  • f
storage when there are n nested recursiv e calls. In man y situations this is v ery w asteful. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-11
SLIDE 11 In tro duction to F unctional Programming: Lecture 6 11 A tail recursiv e v ersion No w, b y con trast, consider the follo wing implemen tation
  • f
the factorial function:
  • fun
tfact x n = if n = then x else tfact (x * n) (n
  • 1);
> val tfact = fn : int
  • >
int
  • >
int
  • fun
fact n = tfact 1 n; > val fact = fn : int
  • >
int
  • fact
6; > val it = 720 : int The recursiv e call is the whole expression; it do es not
  • ccur
as a prop er sub expression
  • f
some
  • ther
expression in v
  • lving
v alues
  • f
v ariables. Suc h a call is said to b e a tail c al l b ecause it is the v ery last thing the calling function do es. A function where all recursiv e calls are tail calls is said to b e tail r e cursive. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-12
SLIDE 12 In tro duction to F unctional Programming: Lecture 6 12 Wh y tail recursion? If a function is tail recursiv e, the compiler is clev er enough to realize that the same area
  • f
storage can b e used for the lo cal v ariables
  • f
eac h instance. W e a v
  • id
using all that stac k. The additional argumen t x
  • f
the tfact function is called an ac cumulator, b ecause it accum ulates the result as the recursiv e calls stac k up, and is then returned at the end. W
  • rking
in this w a y , rather than mo difying the return v alue
  • n
the w a y bac k up, is a common w a y
  • f
making functions tail recursiv e. In a sense, a tail recursiv e implemen tation using accum ulators corresp
  • nds
to an iterativ e v ersion using assignmen ts and while-lo
  • ps.
The
  • nly
dierence is that w e pass the state around explicitly . John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-13
SLIDE 13 In tro duction to F unctional Programming: Lecture 6 13 F
  • rcing
ev aluation (1) Recall that ML do es not ev aluate inside lam b das. Therefore it sometimes pa ys to pull expressions
  • utside
a lam b da when they do not dep end
  • n
the v alue
  • f
the b
  • und
v ariable. F
  • r
example, w e migh t co de the ecien t factorial b y making tfact lo cal:
  • fun
fact n = let fun tfact x n = if n = then x else tfact (x * n) (n
  • 1)
in tfact 1 n end; Ho w ev er the binding
  • f
the recursiv e function to tfact do es not get ev aluated un til fact sees its argumen ts. Moreo v er, it gets reev aluated eac h time ev en though it do esn't dep end
  • n
n. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-14
SLIDE 14 In tro duction to F unctional Programming: Lecture 6 14 F
  • rcing
ev aluation (2) A b etter co ding is as follo ws:
  • val
fact = let fun tfact x n = if n = then x else tfact (x * n) (n
  • 1)
in tfact 1 end; In cases where the sub expression in v
  • lv
es m uc h more ev aluation, the dierence can b e sp ectacular. Most compilers do not do suc h
  • ptimizations
automatically . Ho w ev er it falls under the general heading
  • f
p artial evaluation, a big researc h eld. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-15
SLIDE 15 In tro duction to F unctional Programming: Lecture 6 15 F
  • rcing
ev aluation (3) An alternativ e co ding is to use local: A b etter co ding is as follo ws:
  • local
fun tfact x n = if n = then x else tfact (x * n) (n
  • 1)
in fun fact n = tfact 1 n end; > val fact = fn : int
  • >
int The lo cal declaration is in visible
  • utside
the b
  • dy
  • f
fact. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-16
SLIDE 16 In tro duction to F unctional Programming: Lecture 6 16 Minimizing consing (1) The space used b y t yp e constructors (`cons cells') is not allo cated and deallo cated in suc h as straigh tforw ard w a y as stac k space. In general, it is dicult to w
  • rk
  • ut
when a certain cons cell is in use, and when it is a v ailable for recycling. F
  • r
example in: val l = 1::[] in tl l; the cons cell can b e reused immediately . Ho w ev er if l is passed to
  • ther
functions, it is imp
  • ssible
to decide at compile-time when the cons cell is no longer needed. Therefore, space in functional languages has to b e reclaimed b y analyzing memory p erio dically and deciding whic h bits are needed. The remainder is then reclaimed. This pro cess is kno wn as garb age c
  • l
le ction. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-17
SLIDE 17 In tro duction to F unctional Programming: Lecture 6 17 Minimizing consing (2) W e can
  • ften
mak e programs more space and time ecien t b y reducing consing. One simple tric k is to reduce the usage
  • f
append. By lo
  • king
at the denition:
  • fun
append [] l = l | append (h::t) l = h::(append t l); > val append = fn : 'a list
  • >
'a list
  • >
'a list w e can see that it generates n cons cells where n is the length
  • f
the rst argumen t. F
  • r
example, this implemen tation
  • f
rev ersal:
  • fun
rev [] = [] | rev (h::t) = append (rev t) [h]; > val rev = fn : 'a list
  • >
'a list is v ery inecien t, generating ab
  • ut
n 2 =2 cons cells, where n is the length
  • f
the list. John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998
slide-18
SLIDE 18 In tro duction to F unctional Programming: Lecture 6 18 Minimizing consing (3) A far b etter v ersion is:
  • local
fun reverse [] acc = acc | reverse (h::t) acc = reverse t (h::acc) in fun rev l = reverse l [] end; > val rev = fn : 'a list
  • >
'a list This
  • nly
generates n cons cells, and has the additional merit
  • f
b eing tail recursiv e, so w e sa v e stac k space. One can also a v
  • id
consing in pattern-matc hing b y using as, e.g. instead
  • f
rebuilding a cons cell: fn [] => [] | (h::t) => if h < then t else h::t; using fn [] => [] | (l as h::t) => if h < then t else l; John Harrison Univ ersit y
  • f
Cam bridge, 27 Jan uary 1998