Concepts of Programming Languages

(Sean Pound) #1

15.7 ML 705


can. Actually, if you do rebind a name with a second val statement, it causes a
new entry in the evaluation environment that is not related to the previous ver-
sion of the name. In fact, after the new binding, the old evaluation environment
entry (for the previous binding) is no longer visible. Also, the type of the new
binding need not be the same as that of the previous binding. val statements
do not have side effects. They simply add a name to the current evaluation
environment and bind it to a value.
The normal use of val is in a let expression.^10 Consider the following
example:

let
val radius = 2.7
val pi = 3.14159
in
pi * radius * radius
end;

ML includes several higher-order functions that are commonly used in func-
tional programming. Among these are a filtering function for lists, filter,
which takes a predicate function as its parameter. The predicate function is often
given as a lambda expression, which in ML is defined exactly like a function,
except with the fn reserved word, instead of fun, and of course the lambda
expression is nameless. filter returns a function that takes a list as a param-
eter. It tests each element of the list with the predicate. Each element on which
the predicate returns true is added to a new list, which is the return value of the
function. Consider the following use of filter:

filter(fn(x) => x < 100, [25, 1, 50, 711, 100, 150, 27,
161, 3]);

This application would return [25, 1, 50, 27, 3].
The map function takes a single parameter, which is a function. The result-
ing function takes a list as a parameter. It applies its function to each element
of the list and returns a list of the results of those applications. Consider the
following code:

fun cube x = x * x * x;
val cubeList = map cube;
val newList = cubeList [1, 3, 5];

After execution, the value of newList is [1, 27, 125]. This could be done
more simply by defining the cube function as a lambda expression, as in the
following:

val newList = map (fn x => x * x * x, [1, 3, 5]);


  1. let expressions were introduced in Chapter 5.

Free download pdf