Concepts of Programming Languages

(Sean Pound) #1

704 Chapter 15 Functional Programming Languages


parameter are separated by an OR symbol (|). For example, using pattern
matching, the factorial function could be written as follows:

fun fact(0) = 1
| fact(1) = 1
| fact(n : int): int = n * fact(n − 1);

If fact is called with the actual parameter 0 , the first definition is used; if
the actual parameter is 1, the second definition is used; if an int value that is
neither 0 nor 1 is sent, the third definition is used.
As discussed in Chapter 6, ML supports lists and list operations. Recall that
hd, tl, and :: are ML’s versions of Scheme’s CAR, CDR, and CONS.
Because of the availability of patterned function parameters, the hd and tl
functions are much less frequently used in ML than CAR and CDR are used in
Scheme. For example, in a formal parameter, the expression

(h :: t)

is actually two formal parameters, the head and tail of given list parameter,
while the single corresponding actual parameter is a list. For example, the num-
ber of elements in a given list can be computed with the following function:

fun length([]) = 0
| length(h :: t) = 1 + length(t);

As another example of these concepts, consider the append function,
which does what the Scheme append function does:

fun append([], lis2) = lis2
| append(h :: t, lis2) = h :: append(t, lis2);

The first case in this function handles the situation of the function being called
with an empty list as the first parameter. This case also terminates the recur-
sion when the initial call has a nonempty first parameter. The second case of
the function breaks the first parameter list into its head and tail (hd and tl).
The head is CONSed onto the result of the recursive call, which uses the tail as
its first parameter.
In ML, names are bound to values with value declaration statements of
the form
val new_name = expression;
For example,
val distance = time * speed;
Do not get the idea that this statement is exactly like the assignment statements
in the imperative languages, for it is not. The val statement binds a name to a
value, but the name cannot be later rebound to a new value. Well, in a sense it
Free download pdf