15.08.2013 Views

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

- fun both_plus (x:int,y:int) = fn (z:int) => x + y + z;<br />

val both_plus int * int -> int -> int<br />

cascaded_plus 4 5;<br />

Another simplification (related to those above)<br />

- fun cascaded_plus x y = x + y;<br />

val cascaded_plus : int -> int -> int<br />

c○: Michael Kohlhase 70<br />

e EdNote: Generla Problem: how to mark up SML syntax?<br />

Folding Procedures<br />

Definition 102 SML provides the left folding operator to realize a recurrent computation<br />

schema<br />

foldl : (’a * ’b -> ’b) -> ’b -> ’a list -> ’b<br />

foldl f s [x1,x2,x3] = f(x3,f(x2,f(x1,s)))<br />

We call the procedure f the iterator and s the start value<br />

Example 103 Folding the iterator op+ with start value 0:<br />

foldl op+ 0 [x1,x2,x3] = x3+(x2+(x1+0))<br />

x3<br />

x3<br />

f<br />

x2<br />

+<br />

x2<br />

f<br />

x1<br />

+<br />

f<br />

+<br />

s<br />

x1 0<br />

Thus the procedure fun plus xs = foldl op+ 0 xs adds the elements of integer lists.<br />

Folding Procedures (continued)<br />

Example 104 (Reversing Lists)<br />

c○: Michael Kohlhase 71<br />

foldl op:: nil [x1,x2,x3]<br />

= x3 :: (x2 :: (x1:: nil))<br />

Thus the procedure fun rev xs = foldl op:: nil xs reverses a list<br />

c○: Michael Kohlhase 72<br />

40<br />

x3<br />

::<br />

x2<br />

::<br />

::<br />

x1 n

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!