Functions as Data
In ML functions are first-class objects: they can be passed as arguments, returned as values, and incorporated as components of compound values. Sometimes this can be an effective way of representing data; in particular, it allows a common interface to be provided for similar functions on differently represented datatypes. By including these functions as part of the representation of an object, we can implement some features of an “object-oriented” programming style in ML. We will return to this use of functions as data later in the course. We can also use functions to represent infinite datastructures, such as the sequence of all prime numbers. Again, we will return to this topic later in the course.
In this note, we are more interested in the use of functional representations to provide “executable specifications” of some datatypes that we will later implement in a more traditional fashion. We give some examples that make use of functions as values.
Dictionaries
Our first example is an implementation of the Dictionary signature.
Consider a dictionary, like the telephone dictionary, with strings as keys, and numbers as entries. Given a string, we can use the dictionary to lookup the corresponding number. This gives us a (partial) function from strings to numbers. We can use functions to implement dictionaries directly.
|
.
A more common implementation of a dictionary is as an association list, a list of associated pairs. Mathematicians call the set of such pairs the graph of the function; this may be confusing, as in computer science we use the term graph for a related, but more general, notion.
|
Sets
A set may be represented by a boolean-valued function, or predicate, of type Item -> bool, that tells us whether a given item is a member of the set.
|
This gives an implementation of most of the set operations. However, we cannot implement IsEmpty, since there is no way to test whether a given function will always return the answer false. One benefit of this representation is that it allows us to represent infinite sets, such as the set of even numbers.
©Michael Fourman 1994-2006