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.

- identity(5);<br />

val it = 5 : int<br />

Example 97 returning functions: (again, functions are normal values.)<br />

- val constantly = fn k => (fn a => k);<br />

- (constantly 4) 5;<br />

val it = 4 : int<br />

- fun constantly k a = k;<br />

c○: Michael Kohlhase 68<br />

One of the neat uses of higher-order function is that it is possible to re-interpret binary functions as<br />

unary ones using a technique called “Currying” after the Logician Haskell Brooks Curry (∗(1900),<br />

†(1982)). Of course we can extend this to higher arities as well. So in theory we can consider<br />

n-ary functions as syntactic sugar for suitable higher-order functions.<br />

Cartesian and Cascaded Procedures<br />

We have not been able to treat binary, ternary,. . . procedures directly<br />

Workaround 1: Make use of (Cartesian) products (unary functions on tuples)<br />

Example 98 +: Z × Z → Z with +(〈3, 2〉) instead of +(3, 2)<br />

fun cartesian_plus (x:int,y:int) = x + y;<br />

cartesian_plus : int * int -> int<br />

Workaround 2: Make use of functions as results<br />

Example 99 +: Z → Z → Z with +(3)(2) instead of +(3, 2).<br />

fun cascaded_plus (x:int) = (fn y:int => x + y);<br />

cascaded_plus : int -> (int -> int)<br />

Note: cascaded_plus can be applied to only one argument: cascaded_plus 1 is the function<br />

(fn y:int => 1 + y), which increments its argument.<br />

c○: Michael Kohlhase 69<br />

SML allows both Cartesian- and cascaded functions, since we sometimes want functions to be<br />

flexible in function arities to enable reuse, but sometimes we want rigid arities for functions as<br />

this helps find programming errors.<br />

Cartesian and Cascaded Procedures (Brackets)<br />

Definition 100 Call a procedure Cartesian, iff the argument type is a product type, call it<br />

cascaded, iff the result type is a function type.<br />

Example 101 the following function is both Cartesian and cascading<br />

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

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

Convenient: Bracket elision conventions<br />

e1 e2 e3 (e1 e2) e3 5 (procedure application associates to the left)<br />

τ1 → τ2 → τ3 τ1 → (τ2 → τ3) (function types associate to the right)<br />

SML uses these elision rules<br />

39

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

Saved successfully!

Ooh no, something went wrong!