3.2 A Simple Functional Programming Language 59
list. The function map is a higher-order function, since it expects a function as an
argument.
Letusnotethatbesidesthepuristicsyntaxusedsofar,theprogramminglanguage
OC
AML also allowsustolisttheformalparametersinafunctiondefinitionfollowing
the function name:
let rec map fl
= match l with
[] → []
|
x :: xs → fx:: map f xs
Polymorphism. Types in functional programming languages are often represented
as terms. Basic types are atomic terms, such as int, bool. Structured types, such as
lists, are described by type terms. A list of int values is, for example, described by
int list. An expression may have more than one possible type. In OC
AML,thesetof
possible types of an expression can be described by a type scheme. A type scheme
may contain type variables, which may be instantiated to different types at different
uses of the expression. The type scheme for an expression can be specified by a
declaration or be derived by a type inference algorithm. A type inference algorithm
derives, for all expressions for which the programmer has not specified a type, a type
scheme,which is as general as possible (often the most general) and then verifiesthat
all expressions are used according to their types. The function map, for example, has
the polymorphic type:
map :
(
a →
b) →
a list →
b list
The type variables
a,
b stand for any types. This means that the function map can
be used for an int function and an int list, as well as for a Boolean function and a list
of Boolean values. The type of map only requires that the argument type of the first
functional argument agrees with the type of the elements of the second argument,
which is a list. The result then has a list type, where the list elements have the type
of the result of the functional argument.
In the following sections, we present a simple functional fragment F
ULof
OC
AML as well as the architecture of the virtual machine MAMA. Then we ex-
plain the instruction set of the M
AMA together with the translation schemes for
the translation of F
ULinto M AMA code. After a description of the architecture, the
translation is explained for simple expressions first, as we did in Sect. 2.2.Afterthe
treatment of variables, we proceed in the same spirit as we proceeded for the transla-
tion of C into CM
A code. Novel concepts, though, are needed for implementing lazy
evaluation and higher-order functions.
3.2 A Simple Functional Programming Language
As in Chap. 2, we are interested in code generation for a well-suited virtual machine
rather than in further tasks of compilation such as parsing or type checking. To sim-
plify things, we consider a fragment of the programming language OC
AML, which