in tro duction to f unctional programming lecture 8 1 in
play

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


  1. 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 � Sequencing commands � Exceptions � References � Arra ys � Imp erativ e t yp es John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  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 of 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 e�cien 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 of Cam bridge, 30 Jan uary 1998

  3. In tro duction to F unctional Programming: Lecture 8 3 Output Input-output and other kinds of in teraction with the en vironmen t seem essen tially imp erativ e. F rom a certain p oin t of view, w e can imagine the input and output as p oten tially in�nite streams and handle them in a purely functional st yle | this is done in some lazy languages lik e Miranda or 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-e�ect of in teracting with the en vironmen t. W e will sho w one, 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 of Cam bridge, 30 Jan uary 1998

  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-e�ect, w e care ev en more ab out ev aluation order. 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 op 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 of the whole expression: - (print "first "; print "second\n"); first second > val it = () : unit - (1;2); > val it = 2 : int John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  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 out an `uncaugh t exception'. As the error message suggests, it is p ossible to `catc h' them. There is a t yp e exn of exc eptions , whic h is e�ectiv ely a recursiv e t yp e. Unlik e with ordinary t yp es, one can add new constructors for the t yp e exn at an y p oin t in the program via an exception declaration, e.g. - exception Died; > exn Died = Died : exn - exception Failed of string; > exn Failed = fn : string -> exn John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  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 or example, w e migh t in v en t our o wn exception to co v er the case of taking the head of 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 of Cam bridge, 30 Jan uary 1998

  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 ordinary 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 one view, exceptions are not really imp erativ e features. W e can imagine a hidden t yp e of exceptions tac k ed on to the return t yp e of eac h function. An yw a y , they are often quite useful! John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  8. In tro duction to F unctional Programming: Lecture 8 8 Exceptions (4) Exceptions can normally b e treated just as other ML v alues. F or example, supp ose w e w an t to de�ne a function to \trace" other 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 of Cam bridge, 30 Jan uary 1998

  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-e�ect, mo dify the v alues of these v ariables. They are explicitly accessed via r efer enc es (p oin ters in C parlance) and the p oin ters themselv es b eha v e more lik e ordinary 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 onding reference, i.e. a p oin ter to it. One manipulates the con ten ts via the p oin ter. This is quite similar to C: here one often sim ulates `v ariable parameters' and passes bac k comp osite ob jects from functions via explicit use of p oin ters. T o get at the con ten ts of a ref , use the dereferencing (indirection) op erator ! . T o mo dify its v alue, use := . John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  10. In tro duction to F unctional Programming: Lecture 8 10 References (2) Here is an example of 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 one can pattern-matc h against it. John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  11. In tro duction to F unctional Programming: Lecture 8 11 References (3) References are useful in ML for t w o di�eren t reasons. First, as y ou migh t exp ect, they allo w us to mo dify the state of 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 ould often 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 or cyclic . Whic hev er w a y y ou use them, it is sometimes useful to ha v e reference v ariables inside a function for con v enience or e�ciency , 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 on m ultiple calls. John Harrison Univ ersit y of Cam bridge, 30 Jan uary 1998

  12. In tro duction to F unctional Programming: Lecture 8 12 References (4) F or example, it's ofen con v enien t to memoize or c ache the result of a previous function call, so that if w e get the same argumen t again, w e can return the stored v alue instead of recalculating it. W e start b y de�ning a function to �nd an item in a list of 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 of Cam bridge, 30 Jan uary 1998

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend