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

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

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

In tro duction to F unctional Programming: Lecture 8 1 In tro duction to F unctional Programming John Harrison Univ ersit y of Cam bridge Lecture 8 Imp erativ e features of ML T opics co v ered: Output


slide-1
SLIDE 1 In tro duction to F unctional Programming: Lecture 8 1 In tro duction to F unctional Programming John Harrison Univ ersit y
  • f
Cam bridge Lecture 8 Imp erativ e features
  • f
ML T
  • pics
co v ered:
  • Output
  • Sequencing
commands
  • Exceptions
  • References
  • Arra
ys
  • Imp
erativ e t yp es John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-2
SLIDE 2 In tro duction to F unctional Programming: Lecture 8 2 ML's imp erativ e features ML is not a pure functional programming language. No w at last w e will discuss its imp erativ e features. Whether a certain feature is really imp er ative is partly a matter
  • f
taste. W e group together here some features that ma y not b e found in pure languages. The main reasons for ha ving these features is that they can mak e programs (a) more ecien t and/or (b) easier to write. In an y case, it's hard to imagine doing certain things lik e I/O in ML in a purely functional w a y . John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-3
SLIDE 3 In tro duction to F unctional Programming: Lecture 8 3 Output Input-output and
  • ther
kinds
  • f
in teraction with the en vironmen t seem essen tially imp erativ e. F rom a certain p
  • in
t
  • f
view, w e can imagine the input and
  • utput
as p
  • ten
tially innite streams and handle them in a purely functional st yle | this is done in some lazy languages lik e Miranda
  • r
Hask ell. It's not v ery con v enien t in ML. ML has v arious sp ecial functions whose ev aluation causes a side-eect
  • f
in teracting with the en vironmen t. W e will sho w
  • ne,
the print function whic h prin ts a string:
  • print;
> val it = fn : string
  • >
unit
  • print
"hello"; hello> val it = () : unit
  • print
"goodbye\n"; goodbye > val it = () : unit John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-4
SLIDE 4 In tro duction to F unctional Programming: Lecture 8 4 Sequencing No w that w e ha v e some expressions whose ev aluation causes a side-eect, w e care ev en more ab
  • ut
ev aluation
  • rder.
Since w e kno w the rules, w e can predict for example:
  • let
val x = print "first " in print "second\n" end; first second Ho w ev er, ML also pro vides a sequencing
  • p
eration ; as do most imp erativ e languages lik e Mo dula-3. In e1 ; e2, expression e1 is ev aluated and the result discarded, then e2 is ev aluated and is the v alue
  • f
the whole expression:
  • (print
"first "; print "second\n"); first second > val it = () : unit
  • (1;2);
> val it = 2 : int John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-5
SLIDE 5 In tro duction to F unctional Programming: Lecture 8 5 Exceptions (1) ML's errors, e.g. matc hing failures and division b y zero, are all signalled b y propagating exc eptions:
  • 1
div 0; ! Uncaught exception: ! Div In all these cases the compiler complains ab
  • ut
an `uncaugh t exception'. As the error message suggests, it is p
  • ssible
to `catc h' them. There is a t yp e exn
  • f
exc eptions, whic h is eectiv ely a recursiv e t yp e. Unlik e with
  • rdinary
t yp es,
  • ne
can add new constructors for the t yp e exn at an y p
  • in
t in the program via an exception declaration, e.g.
  • exception
Died; > exn Died = Died : exn
  • exception
Failed
  • f
string; > exn Failed = fn : string
  • >
exn John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-6
SLIDE 6 In tro duction to F unctional Programming: Lecture 8 6 Exceptions (2) One can explicitly generate an exception using the raise construct. raise <exception> F
  • r
example, w e migh t in v en t
  • ur
  • wn
exception to co v er the case
  • f
taking the head
  • f
an empt y list: > exn Head_of_empty = Head_of_empty : exn
  • fun
hd [] = raise Head_of_empty | hd (h::t) = h; > val hd = fn : 'a list
  • >
'a
  • hd(tl
[1]); ! Uncaught exception: ! Head_of_empty John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-7
SLIDE 7 In tro duction to F unctional Programming: Lecture 8 7 Exceptions (3) One can c atch exceptions using <expr> handle <patterns>, where the patterns to matc h exceptions are just as for
  • rdinary
recursiv e t yp es.
  • fun
headstring sl = hd sl handle Head_of_empty => "" | Failed s => "Failure because "^s; > val headstring = fn : string list
  • >
string
  • headstring
["hi","there"]; > val it = "hi" : string
  • headstring
[]; > val it = "" : string On
  • ne
view, exceptions are not really imp erativ e features. W e can imagine a hidden t yp e
  • f
exceptions tac k ed
  • n
to the return t yp e
  • f
eac h function. An yw a y , they are
  • ften
quite useful! John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-8
SLIDE 8 In tro duction to F unctional Programming: Lecture 8 8 Exceptions (4) Exceptions can normally b e treated just as
  • ther
ML v alues. F
  • r
example, supp
  • se
w e w an t to dene a function to \trace"
  • ther
functions:
  • fun
trace name f x = (print ("entering "^name^"\n"); let val y = f x handle ex => (print (name^" gave an exception\n"); raise ex) in (print (name^" finished\n"); y) end); > val trace = fn : string
  • >
('a
  • >
'b)
  • >
'a
  • >
'b
  • fun
hd' l = trace "hd" hd l; > val hd' = fn : 'a list
  • >
'a
  • hd'
[1,2]; entering hd hd finished > val it = 1 : int John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-9
SLIDE 9 In tro duction to F unctional Programming: Lecture 8 9 References (1) ML do es ha v e real assignable v ariables, and expressions can, as a side-eect, mo dify the v alues
  • f
these v ariables. They are explicitly accessed via r efer enc es (p
  • in
ters in C parlance) and the p
  • in
ters themselv es b eha v e more lik e
  • rdinary
ML v alues. One sets up a new assignable memory cell with the initial con ten ts x b y writing ref x. This expression returns the corresp
  • nding
reference, i.e. a p
  • in
ter to it. One manipulates the con ten ts via the p
  • in
ter. This is quite similar to C: here
  • ne
  • ften
sim ulates `v ariable parameters' and passes bac k comp
  • site
  • b
jects from functions via explicit use
  • f
p
  • in
ters. T
  • get
at the con ten ts
  • f
a ref, use the dereferencing (indirection)
  • p
erator !. T
  • mo
dify its v alue, use :=. John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-10
SLIDE 10 In tro duction to F unctional Programming: Lecture 8 10 References (2) Here is an example
  • f
ho w w e can create and pla y with a reference cell:
  • val
x = ref 1; > val x = ref 1 : int ref
  • !x;
> val it = 1 : int
  • x
:= 2; > val it = () : unit
  • !x;
> val it = 2 : int
  • x
:= !x + !x; > val it = () : unit
  • x;
> val it = ref 4 : int ref
  • !x;
> val it = 4 : int In most resp ects ref b eha v es lik e a t yp e constructor, so
  • ne
can pattern-matc h against it. John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-11
SLIDE 11 In tro duction to F unctional Programming: Lecture 8 11 References (3) References are useful in ML for t w
  • dieren
t reasons. First, as y
  • u
migh t exp ect, they allo w us to mo dify the state
  • f
the program as w e go along, in a more con v en tional st yle. If w e didn't use references, functions w
  • uld
  • ften
ha v e to ha v e additional argumen ts. Secondly , they can b e used to construct data structures that are shar e d
  • r
cyclic. Whic hev er w a y y
  • u
use them, it is sometimes useful to ha v e reference v ariables inside a function for con v enience
  • r
eciency , but use them in suc h a w a y that the function as a whole is still a true function, i.e. returns the same v alue
  • n
m ultiple calls. John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-12
SLIDE 12 In tro duction to F unctional Programming: Lecture 8 12 References (4) F
  • r
example, it's
  • fen
con v enien t to memoize
  • r
c ache the result
  • f
a previous function call, so that if w e get the same argumen t again, w e can return the stored v alue instead
  • f
recalculating it. W e start b y dening a function to nd an item in a list
  • f
pairs:
  • exception
Not_found; > exn Not_found = Not_found : exn
  • fun
assoc a [] = raise Not_found | assoc a ((x,y)::rest) = if x = a then y else assoc a rest; > val assoc = fn : ''a
  • >
(''a * 'b) list
  • >
'b John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-13
SLIDE 13 In tro duction to F unctional Programming: Lecture 8 13 References (5) No w w e declare an in ternal reference v ariable store to hold the list
  • f
(x,f(x)) pairs for previously encoun tered calls.
  • fun
cache f = let val store = ref [] in fn x => assoc x (!store) handle Not_found => let val y = f(x) in (store := (x,y)::(!store); y) end end; > val cache = fn : (''a
  • >
'b)
  • >
(''a
  • >
'b) First the cac hed function sees if it's already got the result stored. If so, it returns it. Otherwise, the underlying function is calculated and a new pair put in the store b efore the result is returned. John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-14
SLIDE 14 In tro duction to F unctional Programming: Lecture 8 14 Arra ys (1) As w ell as individual reference cells,
  • ne
can use arra ys. The appropriate functions for handling arra ys need to b e made a v ailable b y:
  • pen
Array; An arra y
  • f
size n, with eac h elemen t initialized to x is created using the follo wing call
  • array(n,x);
One can then read elemen t m
  • f
an arra y a using:
  • sub(a,m);
and write v alue y to elemen t m
  • f
a using:
  • update(a,n,y);
The elemen ts are n um b ered from zero. Th us the elemen ts
  • f
an arra y
  • f
size n are 0; : : : ; n
  • 1.
John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-15
SLIDE 15 In tro duction to F unctional Programming: Lecture 8 15 Arra ys (2) Here is a simple example:
  • val
a = array(5,0); > val a = <array> : int array
  • sub(a,1);
> val it = : int
  • update(a,1,7);
> val it = () : unit
  • sub(a,1);
> val it = 7 : int All reading and writing is constrained b y b
  • unds
c hec king, e.g.
  • sub(a,5);
! Uncaught exception: ! Subscript John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998
slide-16
SLIDE 16 In tro duction to F unctional Programming: Lecture 8 16 Imp erativ e features and t yp es There are unfortunate in teractions b et w een references and let p
  • lymorphism.
F
  • r
example, according to the usual rules, the follo wing should b e v alid, ev en though it writes something as an in teger and reads it as a b
  • lean:
val l = ref []; l := 1; hd(!l) = true ML places restrictions
  • n
the p
  • lymorphic
t yp e
  • f
expressions in v
  • lving
references to a v
  • id
these problems. It w
  • n't
let y
  • u
declare something lik e the ab
  • v
e:
  • val
l = ref []; ! Toplevel input: ! val l = ref []; ! ^^^^^^^^^^^^^^ ! Value polymorphism: Free type variable at top level John Harrison Univ ersit y
  • f
Cam bridge, 30 Jan uary 1998