Cambridge University Press 1.1 Time Clock User Manual


 
2.5. TYPES AND POLYMORPHISM 15
in a nontrivial program, exactly when each subexpression gets evaluated. In the
eager CAML system, one just needs to remember the simple evaluation rules. To
be explicit, they are as follows:
Constants (e.g. predefined values and functions like 1 and +) evaluate to
themselves.
Evaluation stops immediately at expressions of the form fun x -> ..., and
does not look inside them. This only happens when such an expression is
applied to an argument.
When evaluating an application s t, then first both s and t are evaluated.
5
Then, assuming that the evaluated form of s is a function fun x -> ..., the
body is evaluated with each instance of x replaced by the evaluated form of
t. If the evaluated form of s is a built-in function like +, the appropriate
evaluation is performed.
When evaluating if E1 then E2 else E3, first E1 is evaluated, and depend-
ing on whether it yields true or false, either E2 or E3 respectively (and not
the other) is evaluated.
One can regard let x = E1 in E2 as an abbreviation for (fun x -> E2) E1,
and the above evaluation rules then give the right answer: E1 is evaluated, and then
the evaluated form replaces each x in E1, which is then itself evaluated. Let us see
some examples of evaluating expressions:
(fun x -> (fun y -> y + y) x) (2 + 2)
= (fun x -> (fun y -> y + y) x) 4
= (fun y -> y + y) 4
= 4 + 4
= 8
Note that the subterm (fun y -> y + y) x is not reduced, since it is inside the
function abstraction ‘fun x -> ...’. However, terms that are reducible and not so
enclosed in both function and argument get reduced before the function application
itself is evaluated, e.g. the second step in the following:
((fun f x -> f x) (fun y -> y + y)) (2 + 2)
= ((fun f x -> f x) (fun y -> y + y)) 4
= (fun x -> (fun y -> y + y) x) 4
= (fun y -> y + y) 4
= 4 + 4
= 8
The fact that CAML does not evaluate under function abstractions is of crucial
importance to advanced programmers. It gives precise control over the evaluation of
expressions, and can be used to mimic many of the helpful cases of lazy evaluation,
or sometimes to force earlier evaluation of expressions by moving them outside fun
x -> ....
2.5 Types and polymorphism
Some functions do not have a fixed type. For example, the identity function that
returns its argument unchanged doesn’t care whether its argument is an integer, a
5
CAML Light actually evaluates t first.