This preview shows pages 1–3. Sign up to view the full content.
Recitation 3
Higherorder Functions, Anonymous Functions,
Currying, Side effects, Printing and Exceptions
This lecture covers:
•
higherorder functions
•
anonymous functions
•
currying
•
sideeffects and printing
•
exceptions
Higherorder functions
Functions are values just like any other value in OCaml. What does that mean exactly? This means that we
can pass functions around as arguments to other functions, that we can store functions in data structures, that
we can return functions as a result from other functions. The full implication of this will not hit you until
later, but believe us, it will.
Let us look at why it is useful to have higherorder functions. The first reason is that it allows you to write
more general code, hence more reusable code. As a running example, consider functions
double
and
square
on integers:
let double (x:int):int = 2 * x
let square (x:int):int = x * x
Let us now come up with a function to quadruple a number. We could do it directly, but for utterly twisted
motives decide to use the function
double
above:
let quad (x:int):int = double (double (x))
Straightforward enough. What about a function to raise an integer to the fourth power?
let fourth (x:int):int = square (square (x))
There is an obvious similarity between these two functions: what they do is apply a given function twice to a
value. By passing in the function to
apply_twice
as an argument, we can abstract this functionality and
thus reuse code:
let applyTwice ((f:int > int), (x:int)):int = f (f (x))
Using this, we can write:
let quad (x:int):int = applyTwice(double,x)
let fourth (x:int):int = applyTwice(square,x)
The advantage is that the similarity between these two functions has been made manifest. Doing this is very
helpful. If someone comes up with an improved (or corrected) version of
applyTwice
, then every function
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Documentthat uses it profits from the improvement.
The function
applyTwice
is a socalled higherorder function: it is a function from functions to other
values. Notice the type of
applyTwice
is
((int > int) * int) > int
.
To avoid polluting the toplevel namespace, it can be useful to locally define the function to pass in as an
argument. For example:
let fourth (x:int):int =
let square (y:int):int = y * y in
applyTwice (square,x)
What happens when we evaluate an expression that uses a higherorder function? We use the same rules as
This is the end of the preview. Sign up
to
access the rest of the document.
 '07
 GIAMBATTISTA,A

Click to edit the document details