Cambridge University Press 1.1 Time Clock User Manual


 
Chapter 2
A taste of CAML
CAML Light feels rather different from common programming languages like C or
FORTRAN. The major difference is that it is a functional rather than imperative
language. While it does have imperative features, we won’t make very great use
of them. The following section explains the contrast; readers with no previous
programming experience may choose to skip or just skim this material.
2.1 Imperative vs functional programming
Programs in traditional languages, such as FORTRAN, Algol, C and Modula-3,
rely heavily on modifying the values of a collection of variables, called the state.
Before execution, the state has some initial value σ, representing the inputs to
the program, and when the program has finished, the state has a new value σ
including the result(s). During execution, each command changes the state, which
has therefore proceeded through some finite sequence of values:
σ = σ
0
σ
1
σ
2
·· · σ
n
= σ
For example in a sorting program, the state initially includes an array of values,
and when the program has finished, the state has been modified in such a way that
these values are sorted, while the intermediate states represent progress towards
this goal.
The state is typically modified by assignment commands, often written in the
form v = E or v := E where v is a variable and E some expression. These commands
can be executed in a sequential manner by writing them one after the other in the
program, often separated by a semicolon. By using statements like if and while,
one can execute these commands conditionally, and repeatedly, depending on other
properties of the current state. The program amounts to a set of instructions on
how to perform these state changes, and therefore this style of programming is often
called imperative or procedural. Correspondingly, the traditional languages intended
to support it are known as imperative or procedural languages.
Functional programming represents a radical departure from this model. Essen-
tially, a functional program is simply an expression, and execution means evaluation
of the expression.
1
We can see how this might be possible, in general terms, as fol-
lows. Assuming that an imperative program (as a whole) is deterministic, i.e. the
output is completely determined by the input, we can say that the final state, or
whichever fragments of it are of interest, is some function of the initial state, say
1
Functional programming is often called ‘applicative programming’ since the basic mechanism
is the application of functions to arguments.
9