Cambridge University Press 1.1 Time Clock User Manual


 
2.2. BASIC USE OF CAML 11
by two successive semicolons, and it will evaluate them and print the result. In
computing jargon, the CAML system sits in a read-eval-print loop: it repeatedly
reads an expression, evaluates it, and prints the result. For example, CAML can be
used as a simple calculator:
#10 + 5;;
it : int = 15
The system not only returns the answer, but also the type of the expression,
which it has inferred automatically. (We will have more to say about CAML’s
types in a later section.) It can do this because it knows the type of the built-in
addition operator +. On the other hand, if an expression is not typable, the system
will reject it, and try to give some idea about how the types fail to match up. In
complicated cases, the error messages can be quite tricky to understand.
#1 + true;;
Toplevel input:
>let it = 1 + true;;
> ^^^^
This expression has type bool,
but is used with type int.
Since CAML is a functional language, expressions are allowed to be functions.
Functions can be written in CAML using the syntax fun x -> t[x] for the function
that maps an argument x to t[x], the latter being any expression involving x. Such
an expression involving fun x -> ... is said to be a function abstraction. For
example we can define the successor function:
#fun x -> x + 1;;
it : int -> int = <fun>
Again, the type of the expression, this time int -> int, meaning a function
from integers to integers, is inferred and displayed. However the function itself
is not printed; the system merely writes <fun>. This is because, in general, the
internal representations of functions are not very readable.
3
In normal mathematical
notation, application of a function f to an argument x is written f(x). In CAML,
the parentheses can be omitted unless they are needed to enforce grouping, e.g.
#(fun x -> x + 1) 1 * 2;;
it : int = 4
#(fun x -> x + 1) (1 * 2);;
it : int = 3
#((fun x -> x + 1) 1) * 2;;
it : int = 4
Every function in CAML takes just a single argument. However there are two
ways of getting the effect of functions of more than one argument. One way is
to have a single argument but of a more complex type, such as pairs (see later)
of integers. The other is to use ‘currying’ (after the logical Haskell Curry), where
the function takes one argument and yields another function that takes the second
argument, and so on. For example, a curried function of two arguments that adds
the arguments together can be written and used as follows:
3
CAML does not store them simply as syntax trees, but compiles them into bytecode.