Programming Languages and Lambda Calculi
Programming Languages and Lambda Calculi
I Models of Languages 7
Chapter 1: Computing with Text 9
1.1 Defining Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Relations as Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Directed Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Evaluation in Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.6 Evaluation Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Notation Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3
4
Chapter 7: Machines 69
7.1 CC Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2 SCC Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.3 CK Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.4 CEK Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.5 Machine Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Chapter 9: Continuations 89
9.1 Saving Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
9.2 Revised Texual Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
9.3 Revised CEK Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Models of Languages
7
9
In this book, we study how a programming language can be defined in a way that is easily
understood by people, and also amenable to formal analysis—where the formal analysis should
be easily understood by people, too.
One way of defining a language is to write prose paragraphs that explain the kinds of
expressions that are allowed in the language and how they are evaluated. This technique has
an advantage that a reader can quickly absorb general ideas about the language, but details
about the language are typically difficult to extract from prose. Worse, prose does not lend
itself to formal analysis.
Another way of defining a language is to implement an interpreter for it in some meta-
language. Assuming that a reader is familiar with the meta-language, this technique has the
advantage of clearly and completely specifying the details of the language. Assuming that the
meta-language has a formal specification, then the interpreter has a formal meaning in that
language, and it can be analyzed.
The meta-language used to define another language need not execute efficiently, since its
primary purpose is to explain the other language to humans. The meta-language’s primitive
data constructs need not be defined in terms of bits and bytes. Indeed, for the meta-language
we can directly use logic and set theory over a universe of program text. In the same way
that computation on physical machines can be described, ultimately, in terms of shuffling bits
among memory locations, computation in the abstract can be described in terms of relations
on text.
B = t
| f
| (B • B)
then we actually define a set B of textual strings. The above definition can be expanded to the
following constraints on B:
t∈B
f∈B
a ∈ B and b ∈ B ⇒ (a • b) ∈ B
Technically, the set B that we mean is the smallest set that obeys the above constraints.
Notation: we’ll sometimes use “B” to mean “the set B”, but sometimes “B” will mean “an
arbitrary element of B”. The meaning is always clear from the context. Sometimes, we use a
subscript or a prime on the name of the set to indicate an arbitrary element of the set, such as
“B1 ” or “B 0 ”. Thus, the above constraints might be written as
t∈B [a]
f∈B [b]
(B1 • B2 ) ∈ B [c]
Given a particular bit of text that belongs to B, however, we can demonstrate that it is in B by
showing how the constraints that define B require the text to be in B. For example, (t • (f • t))
is in B:
1. t∈B by [a]
2. f∈B by [b]
3. t∈B by [a]
4. (f • t) ∈ B by 2, 3, and [c]
f ∈ B [b] t ∈ B [a]
t∈B [a] (f • t) ∈ B [c]
(t • (f • t)) ∈ B [c]
Also, we’ll tend to omit the names of deployed rules from the tree, since they’re usually obvious:
f∈B t∈B
t∈B (f • t) ∈ B
(t • (f • t)) ∈ B
Exercise 1.1. Which of the following are in B? For each member of B, provide a proof tree
showing that it must be in B.
1. t
2. •
3. ((f • t) • (f • f))
4. ((f) • (t))
1.2 Relations
A relation is a set whose elements consist of ordered pairs.1 For example, we can define the
≡ relation to match each element of B with itself:
a ∈ B ⇒ ha, ai ∈≡
a∈B ⇒ a≡a
or even simply
B1 ≡ B1
as long as it is understood as a definition of ≡. As it turns out, the relation ≡ is reflexive,
symmetric, and transitive:
a relation R is reflexive iff a R a (for any a)
a relation R is symmetric iff a R b ⇒ b R a
a relation R is transitive iff a R b and b R c ⇒ a R c
1 An ordered pair hx, yi can be represented as a set of sets {{x}, {x, y}}.
1.3 Relations as Evaluation 11
(f • B1 ) r B1 [a]
(t • B1 ) r t [b]
Using r , we could define a new relation r by adding the constraint that r is reflexive:
(f • B1 ) r B1 [a]
(t • B1 ) r t [b]
B1 r B1 [c]
The relation r is the reflexive closure of the r relation. We could define yet another relation
by adding symmetric and transitive constraints:
(f • B1 ) ≈r B1 [a]
(t • B1 ) ≈r t [b]
B1 ≈r B1 [c]
B1 ≈r B2 ⇒ B2 ≈r B1 [d]
B1 ≈r B2 and B2 ≈r B3 ⇒ B1 ≈r B3 [e]
The simpler relation r was actually more useful in this sense. Both cases in the definition
of r map an expression to a smaller expression. Also, for any expression B, either B is t or f,
or r relates B to at most one other expression. As a result, we can think of r as a single-step
reduction, corresponding to the way that an interpreter might take a single evaluation step in
working towards a final value.
We can define ; ;r as the reflexive–transitive closure of r , and we end up with a multi-
step reduction relation. The multi-step relation ; ;r will map each expression to many other
expressions. As it turns out, though, ;
;r maps each expression to at most one of t or f.
It’s sufficient to define ;
;r as “the reflexive–transitive closure of r ”. An alternate
formulation would be to expand out the constraints, as in the previous section. A
third way would be to partially expand the constraints, but use r in the definition
of ;;r :
B1 ;
;r B1
B1 r B2 ⇒ B1 ;
;r B2
B1 ;
;r B2 and B2 ;
;r B3 ⇒ B1 ;
;r B3
The relations r and ; ;r are intentionally asymmetric, corresponding to the fact that evaluation
should proceed in a specific direction towards a value. For example, given the expression
(f • (f • (t • f))), we can show a reduction to t:
(f • (f • (t • f))) r (f • (t • f))
r (t • f)
r t
Each blank line in the left column is implicitly filled by the expression in the right column from
the previous line. Each line is then a step in an argument that (f • (f • (t • f))) ; ;r t.
B1 r B2 ⇒ B1 →r B2 [a]
B1 →r B10 ⇒ (B1 • B2 ) →r (B10 • B2 ) [b]
B2 →r B20 ⇒ (B1 • B2 ) →r (B1 • B20 ) [c]
Here, we’re using yet another notation to define a relation. This particular notation is suggestive
of a function, i.e., a relation that maps each element to at most one element. We use the
function notation because evalr must be a function if it’s going to make sense as an evaluator.
The relation r defined in the previous lecture is a function, but how could we prove it? Here’s
a semi-formal argument: The relation r is defined by a pair of constraints. The first constraint
applies to a • expression that starts with f, and the result is determined uniquely by the right-
hand part of the expression. The second constraint applies to a • expression that starts with
t, and the result is determined uniquely as t. Since an expression can start with either f or t,
then only one constraint will apply, and the result is unique.
The above argument is fairly convincing because it relies on a directly observable property
of the expression: whether it is a • expression that starts with f or t. Other claims about
relations over B may not be so simple to prove. For example, it is not immediately obvious
that evalr is a function. The fundamental reason is that B is recursively defined; there is no
way to enumerate all of the interesting cases directly. To prove more general claims, we must
use induction.
Mathematical induction arguments are based on the natural numbers. A claim is proved
for 0, then for n + 1 assuming the claim for n, and then the claim follows for all n. For most
of the proofs we will consider, no natural number n is readily provided for elements of the set
(such as B), but one could be derived for an expression based on the number of steps in an
argument that the expression belongs to the set (as in §1.1).
Instead of finding appropriate numbers for set elements to enable mathematical induction,
however, we will use structural induction, which operates directly on the grammar defining
set elements. The underlying principle is the same.
P = α
| (β⊗P )
| (P P )
Example members of P include α, (β ⊗ α), (α α), and ((β ⊗ (β ⊗ α)) (β ⊗ α)). Here is a
claim about elements of P :
The truth of this claim is obvious. But since Theorem 2.1 makes a claim about all possible
instances of P , and since the set of P s is recursively defined, formally it must be proved by
structural induction.
Guideline: To prove a claim about all elements of a recursively defined set, use
structural induction.
The key property of a correctly constructed induction proof is that it is guaranteed to cover an
entire set, such as the set of P s. Here is an example, a proof of the above claim:
• Base cases:
16 Chapter 2: Structural Induction
– Case α
α contains 0 βs and 0 ⊗s, so the claim holds.
• Inductive cases:
– Case (β⊗P )
By induction, since P is a substructure of (β⊗P ), P contains an equal
number—say, n—of βs and ⊗s. Therefore, (β⊗P ) contains n + 1 βs and
⊗s, and the claim holds.
– Case (P1 P2 )
By induction, P1 contains an equal number—say, n1 —of βs and ⊗s. Sim-
ilarly, P2 contains n2 βs and ⊗s. Therefore, (P1 P2 ) contains n1 + n2 βs
and ⊗s, and the claim holds.
The above proof has a relatively standard shape. The introduction, “by induction on the
structure of P ” encapsulates a boilerplate argument, which runs as follows:
The claim must hold for any P . So assume that an arbitrary P is provided. If P
has the shape of a base case (i.e., no substructures that are P s) then we show how
we can deduce the claim immediately. Otherwise, we rely on induction and assume
the claim for substructures within P , and then deduce the claim. The claim then
holds for all P by the principle of structural induction.
The proof for Theorem 2.1 contains a single base case because the definition of P contains
a single case that is not self-referential. The proof contains two inductive cases because the
definition of P contains two self-referential cases.
Guideline: For a structural induction proof, use the standard format. The section
for base cases should contain one case for each base case in the set’s definition. The
section for induction cases should contain one case for each remaining case in the
set’s definition.
The standard shape for a structural induction proof serves as a guide for both the proof writer
and the proof reader. The proof writer develops arguments for individual cases one by one.
The proof reader can then quickly check that the proof has the right shape, and concentrate
on each case to check its correctness separately.
Occasionally, within the section for base cases or induction cases in a proof, the case split
uses some criteria other than the structure used for induction. This is acceptable as long as
the case split merely collapses deeply nested cases, as compared to a standard-format proof. A
non-standard case split must cover all of the base or inductive cases in an obvious way.
All proofs over the structure of P , including Theorem 2.1, have the same outline:
Proof for Theorem : By induction on the structure of P .
• Base cases:
– Case α
···
• Inductive cases:
– Case (β⊗P )
· · · By induction, [claim about P ] . . .
– Case (P1 P2 )
· · · By induction, [claim about P1 ] and, by induction, [claim about P2 ] · · ·
Only the details hidden by “· · ·” depend on the claim being proved. The following claim is also
about all P s, so it will have the same outline as above.
2.2 Definitions with Ellipses 17
• Base case:
– Case α
The claim obviously holds.
• Inductive case:
– Case (βW0 W1 . . . Wn )
Each Wi contains α, and W contains at least one Wi , so the claim holds.
The following theorem can also be proved reasonably without resorting to mutual induction.
Theorem 2.4: For any W , each β in W is preceded by an open parenthesis.
When 4P appears above a line in a definition, we understand it to mean that there must
be a pointy proof tree in its place with 4P at the bottom. This convention is used in the
self-referential second rule.
Both notations simultaneously define two sets: the set of pointy indications 4P , and the set
of pointy proof trees. Nevertheless, both sets are simply patterns of symbols, defined recursively.
Examples of pointy proof trees include the following:
4α 4α
4α 4(α α)
4α 4(α (α α))
We can now write claims about 4P and its pointy proof trees:
Theorem 2.5: If 4P , then the pointy proof tree for 4P contains an odd number
of 4s.
The proof for this claim works just like the proof of a claim on P , by structural induction:
Proof for Theorem 2.5: By induction on the structure of the pointy proof of
4P .
• Base cases:
– Case 4α
The complete tree contains 4α, a line, and a check mark, which is one 4
total, so the claim holds.
• Inductive cases:
– Case 4(P1 P2 )
The complete tree contains 4(P1 P2 ), plus trees for 4P1 and 4P2 . By in-
duction, since the tree for 4P1 is a substructure of the tree for 4(P1 P2 ),
the 4P1 tree contains an odd number of 4s. Similarly, the 4P2 tree con-
tains an odd number of 4s. Two odd numbers sum to an even number, so
the trees for 4P1 and 4P2 combined contain an even number of 4s. But
the complete tree for 4(P1 P2 ) adds one more, giving an odd number of
4s total, and the claim holds.
• Base cases:
– Case 4α
In this case, P is α, and the claim holds.
• Inductive cases:
– Case 4(P1 P2 )
By induction, P1 and P2 each contain no βs, so (P1 P2 ) contains no βs.
Exercise 2.3. Prove Theorem 2.7. The theorem must be proved over a different structure than
Theorem 2.6.
Like our original definition for 4P , P P is defined by the least set satisfying the above rules.
Examples for this set include ((β ⊗α) α)(β ⊗α) and (((β ⊗α) α)β(α α))((β ⊗α)β(α α)).
The atomic elements of the definition in this case are the first three rules, and the self-reference
occurs in the last two rules.
• Base cases:
– Case ((β ⊗ α) α) (β ⊗ α)
In this case, P is ((β ⊗ α) α), which has one , and P 0 is (β ⊗ α), which
has zero s, so the claim holds.
– Case (α (β ⊗ α)) α
In this case, P is (α (β ⊗ α)), which has one , and P 0 is α, which has
zero s, so the claim holds.
– Case (α α) α
In this case, P is (α α), which has one , and P 0 is α, which has zero
s, so the claim holds.
• Inductive cases:
20 Chapter 2: Structural Induction
Exercise 2.6. Prove Theorem 2.11. The proof can proceed in two different ways, since the
implicit “for all” applies to both 4P and P P 0 .
21
Now that we have structural induction, we’re ready to return to the issue of evalr ’s consistency
as an evaluator. In other words, we’d like to prove that evalr is a function. More formally,
given a notion of results R:
R = t
| f
we’d like to prove the following theorem:
To prove the theorem, we can assume evalr (B0 ) = R1 and evalr (B0 ) = R2 for some B0 , R1 ,
and R2 , and we’d like to conclude that R1 = R2 . By the definition of evalr , our assumption
implies that B0 =r R1 and B0 =r R2 (using =r , not =). Hence, by the definition of =r as
an equivalence relation, R1 =r R2 . To reach the conclusion that R1 = R2 , we must study the
nature of calculations, which is the general shape of proofs M =r N when M, N ∈ B.
Since =r is an extension of the one-step reduction →r , a calculation to prove M =r N is
generally a series of one-step reductions based on r in both directions:
M r rN
L3 L5
@
Rr
@ r ... r
L1
@ HH
Rr
@ H j r
H
L2 L4
where each Ln ∈ B. Possibly, these steps can be rearranged such that all reduction steps go
from M to some L and from N to the same L. In other words, if M =r N perhaps there is an
expression L such that M →→r L and N →→r L.
If we can prove that such an L always exists, the proof of consistency is finished. Recall
that we have
R1 =r R2
By the (as yet unproved) claim, there must be an expression L such that
R1 →
→r L and R2 →
→r L
But elements of R, which are just t and f, are clearly not reducible to anything except them-
selves. So L = R1 and L = R2 , which means that R1 = R2 .
By the preceding argument we have reduced the proof of evalr ’s consistency to a claim
about the shape of arguments that prove M =r N . This crucial insight about the connection
between a consistency proof for a formal equational system and the rearrangement of a series
of reduction steps is due to Church and Rosser, who used this idea to analyze the consistency
of a language called the λ-calculus (which we’ll study soon). In general, an equality relation
on terms generated from some basic notion of reduction is Church-Rosser if it satisfies the
rearrangement property.
Since we’re given a particular M =r N , and since the definition of =r is recursive, we can prove
the theorem by induction of the structure of the derivation of M =r N .
22 Chapter 3: Consistency of Evaluation
Lr
@
@
@
M r
R r
@
N
@
@
@
R r
@
L0
To prove this theorem, it will be helpful to first prove a diamond-like property for →r :
Lemma 3.4 [Diamond-like Property for →r ]: If L →r M and L →r N , then
either
• M = N,
• N ∈ R and M →r N ,
23
• M ∈ R and N →r M , or
• there exists an L0 such that M →r L0 and N →r L0 .
To prove this lemma, we consider the given L →r M and note that →r is recursively defined:
• Base case:
– Case L r M
By the definition of r , there are two subcases.
∗ Case L = (f • B0 ) and M = B0
The expression L might be reduced in two ways with →r for N : to
B0 , or to (f • B00 ) with B0 →r B00 .
If N = B0 , then M = N and the clain holds.
Otherwise, N = (f • B00 ). Then, since M = B0 , M →r B00 , and by the
definition of r , N →r B00 . Thus, the claim holds with L0 = B00 .
∗ Case L = (t • B0 ) and M = t
Similar to the previous case; either N = M or N = (t • B00 ) so that
N →r M with M ∈ R.
• Inductive cases; without loss of generality, assume L 6 r N (otherwise swap N
and M ).
– Case L = (B1 • B2 ), B1 →r B10 , and M = (B10 • B2 )
Either M = N (and the claim holds) or N = (B1 • B20 ) with B2 →r B20 .
Assuming the latter, since B1 →r B10 , N →r (B10 • B20 ). Similarly, M →r
(B10 • B20 ). Thus, the claim holds with L0 = (B10 • B20 ).
– Case L = (B1 • B2 ), B2 →r B20 , and M = (B1 • B20 )
Analogous to the previous case.
Now that we know that the one-step reduction satisfies a diamond-like property, we can show
that its transitive–reflexive closure satifies the diamond property. Assume that L →
→r M and
L→→r N . By the inductive definition of the reduction relation → →r ,
L →m
r M and L →nr N
N1 r
?
N2 r
?
?
..
.
N r
?
Using the diamond-like property for the one-step reduction, we can now fill in expressions L11 ,
L21 , L12 , etc. until the entire square is filled out:
24 Chapter 3: Consistency of Evaluation
-Mr1 -Mr2 - . . .
M
L r - r
...
r r r L12
? ? ?
N1 - -
L11 ...
N2 r - r .
? ?
L21 ..
?.
.
.. .
.
N r
?
The B language is too restrictive to be useful for any real programming task. Since it has no
abstraction capability—i.e., no ability to define functions—it is not remotely as powerful as a
realistic programming language.
In this chapter, we study a language called the λ-calculus, which was invented by Church.
Although the syntax and reduction relations for the λ-calculus are minimal, it is closely related
to useful languages like Scheme and ML. In those languages, functions not only manipulate
booleans, integers, and pairs, but also other functions. In other words, functions are values.
For example, the map function consumes a function and a list of elements, and applies the
function to each element of the list. Similarly, a derivative function might take a function
(over real numbers) and return a new function that implements its derivative.
In the λ-calculus, the only kind of value is a function, but we will see how other kinds of
values (including booleans, integers, and pairs) can be defined in terms of functions.
∀x ∈ A, f (x) = x
or
A −→ A
f:
x 7→ x
in the λ-calculus syntax, we write
(λx.x)
An informal reading of the expression (λx.x) says: “if the argument is called x, then the output
of the function is x,” In other words, the function outputs the datum that it inputs.
To write down the application of a function f to an argument a, the λ-calculus uses ordinary
mathematical syntax, modulo the placement of parentheses:
(f a)
For example, the expression representing the application of the identity function to a is:
((λx.x) a)
((λx.x) (λx.x))
Here is an expression representing a function that takes an argument, ignores it, and returns
the identity function:
(λy.(λx.x))
Here is an expression representing a function that takes an argument and returns a function; the
returned function ignores its own argument, and returns the argument of the original function:
(λy.(λx.y))
26 Chapter 4: The λ-Calculus
The λ-calculus supports only single-argument functions, but this last example shows how a
function can effectively take two arguments, x and y, by consuming the first argument, then
returning another function to get the second argument. This technique is called currying.
In conventional mathematical notation, f (a) can be “simplified” by taking the expression for
the definition of f , and substituting a everywhere for f ’s formal argument. For example, given
f (x) = x, f (a) can be simplified to a. Simplification of λ-calculus terms is similar: ((λx.x) a)
can be simplified to a, which is the result of taking the body (the part after the dot) of (λx.x),
and replacing the formal argument x (the part before the dot) with the actual argument a.
Here are several examples:
M, N, L = X
| (λX.M )
| (M M )
X = a variable: x, y, . . .
x (x y) ((x y) (z w))
(λx.x) (λy.(λz.y))
(f (λy.(y y))) ((λy.(y y)) (λy.(y y)))
The first example, x, has no particular intuitive meaning, since x is left undefined. Similarly,
(x y) means “x applied to y”, but we cannot say more, since x and y are undefined. In
contrast, the example (λx.x) corresponds to the identity function. The difference between the
last example and the first two is that x appears free in the first two expressions, but it only
appears bound in the last one.
The relation FV, maps an expression to a set of free variables in the expression. Intuitively,
x is a free variable in an expression if it appears outside of any (λx. ). More formally, we define
the relation FV as follows:
FV( X ) = {X}
FV( (λX.M ) ) = FV(M ) \ {X}
FV( (M1 M2 ) ) = FV(M1 ) ∪ FV(M2 )
FV( x) = {x}
FV( (x (y x)) ) = {x, y}
FV( (λx.(x y)) ) = {y}
FV( (z (λz.z)) ) = {z}
Before defining a reduction relation on λ-calculus expressions, we need one more auxilliary
relation to deal with variable subsitition. The relation [ ← ] maps a source expression, a
variable, and an argument expression to a target expression. The target expression is the same
4.2 λ-Calculus Grammar and Reductions 27
as the source expression, except that free instances of the variable are replaced by the argument
expression:
X1 [X1 ← M ] = M
X2 [X1 ← M ] = X2
where X1 6= X2
(λX1 .M1 )[X1 ← M2 ] = (λX1 .M1 )
(λX1 .M1 )[X2 ← M2 ] = (λX3 .M1 [X1 ← X3 ][X2 ← M2 ])
where X1 6= X2 , X3 6∈ FV(M2 )
and X3 6∈ FV(M1 )\{X1 }
(M1 M2 )[X ← M3 ] = (M1 [X ← M3 ] M2 [X ← M3 ])
Examples for [ ← ]:
Finally, to define the general reduction relation n for the λ-calculus, we first define three simple
reduction relations, α, β, and η:
• The α relation renames a formal argument. It encodes the fact that functions like (λx.x)
and (λy.y) are the same function, simply expressed with different names for the argument.
• The η relation encodes the fact that, if a function f takes its argument and immediately
applies the argument to g, then using f is equivalent to using g.
n=α∪β∪η
Here is one of many possible reductions for ((λx.((λz.z) x)) (λx.x)), where the underlined
portion of the expression is the redex (the part that is reduced by n) in each step:
The parentheses in an expression are often redundant, and they can make large expressions
difficult to read. Thus, we adopt a couple of conventions for dropping parentheses, plus one for
dropping λs:
With these conventions, ((λx.((λz.z) x)) (λx.x)) can be abbreviated (λx.(λz.z) x) λx.x, and
the first reduction above can be abbreviated as follows:
(λx.(λz.z) x) λx.x →α
n (λx.(λz.z) x) λy.y
→ηn (λz.z) λy.y
→βn λy.y
Exercise 4.1. Reduce the following expressions with →n until no more →βn reductions are
possible. Show all steps.
• (λx.x)
• (λx.x) =n (λy.y)
• λy.(λx.λy.x) (y y) =n λa.λb.(a a)
.
true = λx.λy.x
.
false = λx.λy.y
.
if = λv.λt.λf.v t f
.
The = notation indicates that we are defining a shorthand, or “macro”, for an expression. The
macros for true, false, and if will be useful if they behave in a useful way. For example, we
would expect that
if true M N =n M
for any M and N . We can show that this equation holds by expanding the macros:
4.4 Encoding Pairs 29
Similarly, if false M N =n N :
Actually, it turns out that (if true) =n true and (if false) =n false. In other words, our repre-
sentation of true acts like a conditional that branches on its first argument, and false acts like
a conditional that branches on its second argument; the if macro is simply for readability.
Exercise 4.3. Show that (if true) =n true and (if false) =n false.
Exercise 4.4. Define macros for binary and and or prefix operators that evaluate in the natural
way with true and false (so that and true false =n false, etc.).
fst (mkpair M N ) =n M
snd (mkpair M N ) =n N
We will also use the notation hM, N i as shorthand for the pair whose first element is M and
whose second element is N . One way to find definitions for mkpair, etc. is to consider what a
hM, N i value might look like.
Since our only values are functions, hM, N i must be a function. The function has to contain
inside it the expressions M and N , and it has to have some way of returning one or the other
to a user of the pair, depending on whether the user wants the first or second element. This
suggests that a user of the pair should call the pair as a function, supplying true to get the first
element, or false to get the second one:
.
hM, N i = λs.if s M N
As mentioned in the previous section, the if function is really not necessary, and the above can
be simplified by dropping the if.
With this encoding, the fst function takes a pair, then applies it as a function to the argument
true:
.
fst = λp.p true
30 Chapter 4: The λ-Calculus
Similarly, snd applies its pair argument to false. Finally, to define mkpair, we abstract the
abbreviation of hM, N i over arbitrary M and N .
.
hM, N i = λs.s M N
.
mkpair = λx.λy.λs.s x y
.
fst = λp.p true
.
snd = λp.p false
Exercise 4.5. Show that mkpair, fst, and snd obey the equations at the beginning of this
section.
The function add1 should take the representation of a number n and produce the representation
of a number n + 1. In other words, it takes a 2-argument function and returns another 2-
argument function; the new function applies its first argument to the second argument n + 1
times. To get the first n applications, the new function can use the old one.
.
add1 = λn.λf.λx.f (n f x)
Like our encoding of true and false, this encoding of numbers turns out to be convenient. To
add two numbers n and m, all we have to do is apply add1 to n m times—and m happens to
be a function that will take add1 and apply it m times!
.
add = λn.λm.m add1 n
The idea of using the number as a function is also useful for defining iszero, a function that
takes a number and returns true if the number is 0, false otherwise. We can implement iszero by
using a function that ignores its argument and always returns false; if this function is applied
0 times to true, the result will be true, otherwise the result will be false.
.
iszero = λn.n (λx.false) true
To generalize iszero to number equality, we need subtraction. In the same way that addition
can be built on add1, subtraction can be built on sub1. But, although the add1, add, and iszero
functions are fairly simple in Church’s number encoding, sub1 is more complex. The number
function that sub1 receives as its argument applies a function n times, but the function returned
by sub1 should apply the function one less time. Of course, the inverse of an arbitrary function
is not available for reversing one application.
The function implementing sub1 has two parts:
4.6 Recursion 31
• Pair the given argument x with the value true. The true indicates that an application of
f should be skipped.
• Wrap the given function f to take pairs, and to apply f only if the pair contains false.
Always return a pair containing false, so that f will be applied in the future.
.
wrap = λf.λp.hfalse, if (fst p) (snd p) (f (snd p))i
The function sub1 takes an n and returns a new function. The new function takes f and x,
wraps the f with wrap, pairs x with true, uses n on (wrap f ) and htrue, xi, and extracts the
second part of the result—which is f applied to x n − 1 times.
.
sub1 = λn.λf.λx.snd (n (wrap f ) htrue, xi)
A note on encodings: The encoding for 0 is exactly the same as the encoding for false. Thus,
no program can distinguish 0 form false, and programmers must be careful that only true and
false appear in boolean contexts, etc. This is analogous to the way that C uses the same pattern
of bits to implement 0, false, and the null pointer.
Exercise 4.9. Define mult using the technique that allowed us to define add. In other words,
implement (mult n m) as n additions of m to 0 by exploiting the fact that n itself applies a
function n times. Hint: what kind of value is (add m)?
Exercise 4.10. The λ-calculus provides no mechanism for signalling an error. What happens
when sub1 is applied to 0? What happens when iszero is applied to true?
4.6 Recursion
An exercise in the previous section asks you to implement mult in the same way that we
implemented add. Such an implementation exploits information about the way that numbers
are encoded by functions.
Given the functions iszero, add, and sub1 from the previous section, we can also implement
mult without any knowledge of the way that numbers are encoded (which is the way that
programmers normally implement functions). We must define a recursive program that checks
whether the first argument is 0, and if not, adds the second argument to a recursive call that
decrements the first argument.
?
.
mult = λn.λm.if (iszero n) 0 (add m (mult (sub1 n) m))
The problem with the above definition of the macro mult is that it refers to itself (i.e., it’s
recursive), so there is no way to expand mult to a pure λ-calculus expression. Consequently,
the abbreviation is illegal.
32 Chapter 4: The λ-Calculus
This mkmult0 macro is well defined, and (mkmult0 t) produces a multiplication function. . .
assuming that t is a multiplication function! Obviously, we still do not have a multiplication
function. We tried to parameterize the original mult definition by itself, but in doing so we lost
the mult definition.
Although we can’t supply a multiplication function as t, we could instead supply a multi-
plication maker as t. Would that be useful, or do we end up in an infinite regress? As it turns
out, supplying a maker to a maker can work.
Assume that applying a maker to a maker produces a multiplier. Therefore, the initial
argument t to a maker will be a maker. In the body of the maker, wherever a multiplier is
needed, we use (t t)—because t will be a maker, and applying a maker to itself produces a
multiplier. Here is a maker, mkmult1 that expects a maker as its argument:
.
mkmult1 = λt.λn.λm.if (iszero n) 0 (add m ((t t) (sub1 n) m))
If mkmulti1 works, then we can get a mult function by applying mkmulti1 to itself:
.
mult = (mkmult1 mkmult1 )
Let’s try this suspicious function on 0 and m (for some arbitrary m) to make sure that we get
0 back. We’ll expand abbreviations only as necessary, and we’ll assume that abbreivations like
iszero and 0 behave in the expected way:
mult 0 m
= (mkmult1 mkmult1 ) 0 m
→n (λn.λm.if (iszero n) 0 (add m ((mkmult1 mkmult1 ) (sub1 n) m))) 0 m
→n (λm.if (iszero 0) 0 (add m ((mkmult1 mkmult1 ) (sub1 0) m))) m
→n if (iszero 0) 0 (add m ((mkmult1 mkmult1 ) (sub1 0) m))
→→n if true 0 (add m ((mkmult1 mkmult1 ) (sub1 0) m))
→→n 0
mult n m
= (mkmult1 mkmult1 ) n m
→n (λn.λm.if (iszero n) 0 (add m ((mkmult1 mkmult1 ) (sub1 n) m))) n m
→n (λm.if (iszero n) 0 (add m ((mkmult1 mkmult1 ) (sub1 n) m))) m
→n if (iszero n) 0 (add m ((mkmult1 mkmult1 ) (sub1 n) m))
→→n if false 0 (add m ((mkmult1 mkmult1 ) (sub1 n) m))
→→n (add m ((mkmult1 mkmult1 ) (sub1 n) m))
4.6 Recursion 33
Since mult = (mkmult1 mkmult1 ), the last step above can also be written as (add m (mult (sub1 n) m)).
Thus,
mult 0 m → →n 0
mult n m → →n (add m (mult (sub1 n) m)) if n 6= 0
This is exactly the relationship we want among mult, add, sub1, and 0.
Exercise 4.11. Define a macro mksum such that (mksum mksum) acts like a “sum” function
by consuming a number n and adding all the numbers from 0 to n.
The mk definition above is ill-formed, but we can start with this bad definition to get the idea.
The mk function is supposed to take a maker, t, and produce a made function. It does so
by calling the function-expecting maker with (mk t) — which is supposed to create a made
function.
We can fix the circular mk definition using the technique of the previous section:
.
mkmk = λk.λt.t ((k k) t)
.
mk = (mkmk mkmk)
We can check that (mk mkmult0 ) behaves like mult:
(mk mkmult0 ) 0 m
= ((mkmk mkmk) mkmult0 ) 0 m
= (((λk.λt.t ((k k) t)) mkmk) mkmult0 ) 0 m
→n ((λt.t ((mkmk mkmk) t) mkmult0 ) 0 m
→n (mkmult0 ((mkmk mkmk) mkmult0 )) 0 m
→n (λn.λm.if (iszero n) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 n) m))) 0 m
→n (λm.if (iszero 0) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 0) m))) m
→n if (iszero 0) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 0) m))
→→n 0
(mk mkmult0 ) n m
= ((mkmk mkmk) mkmult0 ) n m
= (((λk.λt.t ((k k) t)) mkmk) mkmult0 ) n m
→n ((λt.t ((mkmk mkmk) t) mkmult0 ) n m
→n (mkmult0 ((mkmk mkmk) mkmult0 )) n m
→n (λn.λm.if (iszero n) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 n) m))) 0 m
→n (λm.if (iszero n) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 n) m))) m
→n if (iszero n) 0 (add m (((mkmk mkmk) mkmult0 ) (sub1 n) m))
→→n (add m (((mkmk mkmk) mkmult0 ) (sub1 n) m))
= (add m ((mk mkmult0 ) (sub1 n) m))
34 Chapter 4: The λ-Calculus
mk M = (mkmk mkmk) M
= ((λk.λt.t ((k k) t)) mkmk) M
→n (λt.t ((mkmk mkmk) t) M
→n M ((mkmk mkmk) M )
= M (mk M )
A function that behaves like mk is called a fixed-point operator. The mk function is only
one of many fixed-point operators in the λ-calculus. The more famous one is called Y:1
.
Y = λf.(λx.f (x x)) (λx.f (x x))
In general, Y lets us define recursive functions more easily than the manual technique of Sec-
tion 4.6.1. For example, we can define sum as
.
sum = Y (λs.λn.if (iszero n) 0 (add n (s (sub1 n))))
Since we do not have to repeat a large maker expression, we can skip the intermediate maker
abbreviations mksum, and instead apply Y directly to a maker function.
In addition, a programmer who sees the above definition of sum will immediately note the Y,
see that s is the argument of Y’s argument, and then read λn . . . as the definition of a recursive
function named s.
Exercise 4.13. Define an encoding for Lisp cons cells, consisting of the following macros:
• null, a constant
• cons, a function that takes two arguments and returns a cons cell
• isnull, a function that returns true if its argument is null, false if it is a cons cell
• car, a function that takes a cons cell and returns its first element
• cdr, a function that takes a cons cell and returns its second element
1 The term Y combinator actually refers to the whole family of fixed-point operators. More on this later.
4.7 Facts About the λ-Calculus 35
Your encoding need not assign any particular meaning to expressions such as (car null) or
(car cons).
Exercise 4.14. Using your encoding from the previous exercise, define length, which takes a
list of booleans and returns the number of cons cells in the list. A list of booleans is either null,
or (cons b l) where b is true or false and l is a list of booleans.
A normal form acts like the result of a λ-calculus expression. If an expression has a normal form,
then it has exactly one normal form (possibly via many different reductions). More precisely,
there is one normal form modulo →α n renamings.
There’s no single step that will bring both of the bottom expressions back together. As we’ll
see in the next chapter, the way around this problem is to define a notion of parallel reductions
on independent subexpression, so that both ((λy.y) (λz.z)) sub-expressions on the left can be
reduced at once. For now, though, we will not try to prove Theorem 4.4. Instead, we will
demonstrate the diamond property for a related language in the next chapter.
Unlike expressions in B, where every expression has a result f or t, not every λ-calculus
expression has a normal form. For example, Ω has no normal form:
.
Ω = ((λx.x x) (λx.x x))
Even if an expression has a normal form, then there may be an inifite reduction sequence for
the expression that never reaches a normal form. For example:
(λy.λz.z)((λx.x x) (λw.w w))
→n λz.z normal form
The →n̄ relation is the normal order reduction relation, and it is guaranteed to find a normal
form if one exists.
Theorem 4.5 [Normal Order Reduction]: M has normal form N if and only
if M →
→n̄ N .
Normal-order reduction is also called call-by-name.
Although a normal-order reduction always finds a normal form if it exists, practically no
programming language uses this form of reduction. The reason is that normal order, while is
powerful, is often slow. For example, in the previous diagram showing the non-diamondness of
→n , the reduction on the left corresponds to normal order, but the reduction on the right will
produce the identity function in fewer steps.
In any case, since we have a notion of unique normal form (modulo α-renaming), a natural
question to ask is whether we can define an evaln in the same way as evalr :
?
evaln (M ) = N if M =n N and N is a normal form
The above definition is imprecise with respect to α-renaming, but there is a deeper problem.
As we have seen, there are functions like mk and Y that behave in the same way, but cannot
be reduced to each other. In the next chapter, we will look at a way to resolve this problem.
Exercise 4.15. Prove that ((λx.x x) (λx.x x)) has no normal form.
4.8 History 37
4.8 History
Church invented the lambda calculus slightly before Turning invented Turing machines.
Barendregt [2] provides a comprehensive study of Church’s λ-calculus as a logical system,
and many conventions for the treatment of terms originate with Barendregt. His book provides
numerous techniques applicable to the calculus, though it does not cover λ-calculus as a calculus
for a programming language.
38 Chapter 4: The λ-Calculus
Part II
39
41
Chapter 5: ISWIM
Church developed the λ-calculus as a way of studying all of mathematics, as opposed to me-
chanical computation specifically. In the 1960’s Landin showed that Church’s calculus was,
in fact, not quite an appropriate model of most programming languages. For example, the
λ-calculus expression
(λx.1) (sub1 λy.y)
reduces to (the encoding of) 1, even though most languages would instead complain about
(sub1 λy.y). The problem is not just in the encoding of sub1 and λy.y, but that a β reduction
on the entire expression can ignore the argument (sub1 λy.y) completely.
Whether such call-by-name behavior is desirable or not is open to debate. In any case,
many languages do not support call-by-name. Instead, they support call-by-value, where the
arguments to a function must be fully evaluated before the function is applied.
In this chapter, we introduce Landin’s ISWIM, which more closely models the core of call-
by-value languages such as Scheme and ML. The basic syntax of ISWIM is the same as for the
λ-calculus, and the notions of free variables and substition are the same. Unlike the λ-calculus,
and more like real programming languages, ISWIM comes with a set of basic constants and
primitive operations. But the more fundamental difference is in ISWIM’s call-by-value reduction
rules.
M, N, L, K = X
| (λX.M )
| (M M )
| b
| (on M . . . M )
X = a variable: x, y, . . .
b = a basic constant
on = an n-ary primitive operation
b = {d ne | n ∈ Z}
o1 = {add1, sub1, iszero}
o2 = {+, −, ∗, ↑}
The syntactic object d 1e represents the integer 1. The syntactic object + represents an addition
operator, ↑ is exponentiation, etc. In addition, we define a helpful if0 macro:
.
(if0 K M N ) = (((iszero K) (λX.M ) (λX.N )) d 0e )
where X 6∈ FV(M ) ∪ FV(N )
42 Chapter 5: ISWIM
The FV and [ ← ] relations extend to the new grammar in the obvious way:
FV( b) = {}
FV( X ) = {X}
FV( (λX.M ) ) = FV(M ) \ {X}
FV( (M1 M2 ) ) = FV(M1 ) ∪ FV(M2 )
FV( (on M1 . . . Mn ) ) = FV(M1 ) ∪ . . . FV(Mn )
b[X ← M ] = b
X1 [X1 ← M ] = M
X2 [X1 ← M ] = X2
where X1 6= X2
(λX1 .M1 )[X1 ← M2 ] = (λX1 .M1 )
(λX1 .M1 )[X2 ← M2 ] = (λX3 .M1 [X1 ← X3 ][X2 ← M2 ])
where X1 6= X2 , X3 6∈ FV(M2 )
and X3 6∈ FV(M1 )\{X1 }
(M1 M2 )[X ← M3 ] = (M1 [X ← M3 ] M2 [X ← M3 ])
(on M1 . . . Mn )[X ← M ] = (on M1 [X ← M ] . . . Mn [X ← M ])
V, U, W = b
| X
| (λX.M )
((λX.M ) V ) βv M [X ← V ]
(add1 d me ) b1 d
m + 1e
(sub1 d me ) b1 d
m − 1e
(iszero d 0e ) b1 λxy.x
(iszero d ne ) b1 λxy.y n 6= 0
(+ d me d ne ) b2 d
m + ne
(− d me d ne ) b2 d
m − ne
(∗ d me d ne ) b2 d
m · ne
(↑ d me d ne ) b2 d
mn e
δ = b1 ∪ b2
v = βv ∪ δ
to a value with →v .
The problem is that the argument to f in the outermost application above is not a value—and
cannot be reduced to a value—so (Y f ) never produces the promised fixed-point function.
We can avoid the infinite reduction by changing each application M within Y to (λX.M X),
since the application is supposed to return a function anyway. This inverse-η transformation
puts a value in place of an infinitely reducing application. The final result is the Yv combinator:
Yv = (λf.
(λx.
( (λg. (f (λx. ((g g) x))))
(λg. (f (λx. ((g g) x)))) x)))
The Yv combinator works when applied to a function that takes a function and returns another
one.
Theorem 5.1 [Fixed-Point Theorem for Yv ]: If K = λgx.L, then (K (Yv K)) =v
(Yv K).
44 Chapter 5: ISWIM
Proof for Theorem 5.1: The proof is a straightforward calculation where all of
the basic proof steps are βv steps:
(Yv K)
= ((λf.λx.((λg.(f (λx.((g g) x)))) (λg.(f (λx.((g g) x)))) x)) K)
→v λx.(((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x))))) x)
→v λx.((K (λx.(((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x))))) x))) x)
→v λx.(((λgx.L) (λx.(((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x))))) x))) x)
→v λx.((λx.L[g ← (λx.(((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x))))) x))]) x)
→v λx.L[g ← (λx.((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x)))) x))]
v← ((λgx.L) (λx.((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x)))) x)))
= (K (λx.((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x)))) x)))
v← (K (Yv K))
The proof of Theorem 5.1 looks overly complicated because arguments to procedures must be
values for βv to apply. Thus instead of calculating
λx.((K (λx.(((λg.(K (λx.((g g) x)))) (λg.(K (λx.((g g) x))))) x))) x)
= λx.((K (Yv K)) x)
= λx.((λgx.L) (Yv K)) x)
we need to carry around the value computed by (Yv K). To avoid this complication in the
future, we show that an argument that is provably equal to a value (but is not necessarily a
value yet) can already be used as if it were a value for the purposes of =v .
Theorem 5.2: If M =v V , then for all (λX.N ), ((λX.N ) M ) =v N [X ← M ].
Proof for Theorem 5.2: The initial portion of the proof is a simple calculation:
((λX.N ) M ) =v ((λX.N ) V ) =v N [X ← V ] =v N [X ← M ]
The last step in this calculation, however, needs a separate proof by induction on
N , showing that N [X ← M ] =v N [X ← L] if M =v L:
• Base cases:
– Case N = b
b[X ← M ] = b =v b = b[X ← L].
– Case N = Y
If Y = X, then X[X ← M ] = M =v L = X[X ← L]. Otherwise,
Y [X ← M ] = Y =v Y = Y [X ← L].
• Inductive cases:
– Case N = (λY.N 0 )
If Y = X, then N [M ← X] = N =v N = N [L ← X]. Otherwise, by
induction, N 0 [X ← M ] =v N 0 [X ← L]. Then,
(λY.N 0 )[X ← M ]
= (λY.N 0 [X ← M ])
=v (λY.N 0 [X ← L])
= (λY.N 0 )[X ← L]
– Case N = (N1 N2 )
By induction, Ni [X ← M ] =v Ni [X ← L] for i ∈ [1, 2]. Then,
(N1 N2 )[X ← M ]
= (N1 [X ← M ] N2 [X ← M ])
=v (N1 [X ← L] N2 [X ← L])
= (N1 N2 )[X ← L]
5.4 Evaluation 45
– Case N = (on N1 . . . Nn )
Analogous to the previous case.
5.4 Evaluation
For defining an evaluator, functions as values pose just as much of a problem for ISWIM as for
the λ-calculus. For example, the expression
(λx.x) (λy.(λx.x) d 0e )
A = b ∪ {function}
If evalv (M ) does not exist, we say that M diverges. For example, Ω diverges.
Exercise 5.2. Suppose that we try to strengthen the evaluation function as follows:
b if M =v b
eval1 (M ) = function1 if M =v λX.N N 6= λY.N 0 for any Y, N 0
function+ if M =v λX.λY.N
5.5 Consistency
The definition of ISWIM’s evaluator relies on an equational calculus for ISWIM. Although the
calculus is based on intuitive arguments and is almost as easy to use as a system of arithmetic, it
is far from obvious whether the evaluator is a function that always returns a unique answer for
a program. But for a programmer who needs a deterministic, reliable programming language,
this fact is crucial and needs to be established formally. In short, we need to modify the
consistency theorem of evalr for ISWIM’s evalv . The proof of this theorem turns out to be far
more complex than the one for evalr , though it follows the same outline.
We start with the basic theorem asserting the Church-Rosser property for ISWIM’s calculus.
Proof for Theorem 5.3: Assume that the Church-Rosser Property holds: if
M =v N then there exists an expression L such that M →
→v L and N →
→v L.
Let evalv (M ) = A1 and evalv (M ) = A2 for answers A1 and A2 . We need to show
that A1 = A2 . Based on the definition of ISWIM answers, we distinguish two cases:
• Case A1 ∈ b, A2 ∈ b
It follows from Church-Rosser that two basic constants are provably equal if
and only if they are identical, since neither is reducible.
• Case A1 = function, A2 ∈ b
By the definition of evalv , M =v A2 and M =v λx.N for some N , so A2 =v
λx.N . Again by Church-Rosser and the irreducibility of constants, λx.N →
→v A2 .
But by definition of the reduction relation → →v , λx.N → →v K implies that
K = λx.K 0 . Thus it is impossible that λx.N reduces to A2 , which means that
the assumptions of the case are contradictory.
• Case A1 ∈ b, A2 = function
Analogous to the previous case.
• Case A1 = function, A2 = function
Then A1 = A2 .
These are all possible cases, and hence, it is always true that A1 = A2 , so evalv is
a function.
By the preceding proof, we have reduced the consistency property to the Church-Rosser property
for ISWIM.
Proof for Theorem 5.4: The proof is essentially a replica of the proof for =r
(Theorem 3.2). It assumes a diamond property for the reduction relation →
→v .
After disposing of the Consistency and Church-Rosser theorems, we have arrived at the core of
the problem. Now we need to show the diamond property for ISWIM.
For →→r , a diamond-like property holds for the single-step relation →r , from which the diamond
property for the transitive closure easily follows. But, analogous to the example in the previous
chapter, it is clear that the diamond property cannot hold for →v . The βv reduction can copy
redexes in the argument of a function, which prevents the existence of the common contractum
in certain diamonds. For an example, consider the expression
which contains the two overlapping and underlined βv -redexes. By one or the other of one of
them, we get the expressions
((λx.(x x)) (λy.(λx.x)))
and
((λy.((λx.x) (λx.x))) (λy.((λx.x) (λx.x))))
Both expressions contain redexes, but as the following diagram shows, the one-step reductions
starting from these expressions do not lead to a common expression.
5.5 Consistency 47
((λx.(x x))(λy.((λx.x)(λx.x))))
H
HH
H
HH j
((λy.((λx.x)(λx.x))) ((λx.(x x))(λy.(λx.x)))
(λy.((λx.x)(λx.x))))
HH
H
HH
H ?
HH
H ((λy.(λx.x))
HH (λy.(λx.x))
? j
H
(λy.((λx.x) ((λy.(λx.x)) ((λy.((λx.x)(λx.x))))
(λx.x))) (λy.((λx.x)(λx.x)))) (λy.(λx.x))
Hence, the one-step relation →v does not satisfy the diamond property.
Since the problem of the one-step relation based on v is caused by reductions that duplicate
redexes, we consider an extension ,→v of the one-step reduction →v that contracts several
non-overlapping redexes in parallel. If this extension satisfies the diamond property, and if its
transitive–reflexive closure is the same as that of →v , then we can prove the diamond property
for the →→v reduction.
The parallel extension ,→v is defined as follows:
M ,→v N if M =α N
(on b1 . . . bn ) ,→v δ(on , b1 , . . . bn ) if δ(on , b1 , . . . bn ) is defined
((λX.M ) N ) ,→v M 0 [X ← V ] if M ,→v M 0 and N ,→v V
0 0
(M N ) ,→v (M N ) if M ,→v M 0 and N ,→v N 0
0
(λX.M ) ,→v (λx.M ) if M ,→v M 0
(on M1 . . . Mn ) ,→v (o M1 . . . Mn ) if Mi ,→v Mi0 , i ∈ [1, n]
n 0 0
Proof for Theorem 5.6: By induction on the structure of the proof tree of
L ,→v M .
• Base cases:
– Case L =α M
Set K = N , and the claim holds.
– Case L = (on b1 . . . bn ), M = δ(on , b1 , . . . bn )
Since δ is a function there is no other possible reduction for L; set K =
N = M.
• Inductive cases:
– Case L = ((λX.M0 ) L1 ), M = M00 [X ← V ], M0 ,→v M00 , L1 ,→v V
There are two possiblities for the reduction path L ,→v N . Either the two
parts of the application merely reduce separately, or the application is also
reduced via βv :
48 Chapter 5: ISWIM
Exercise 5.5. Prove that the transitive–reflexive closure of the parallel reduction ,→v is the
same as →
→v . This fact, along with Theorem 5.6, supports the proof of Theorem 5.5.
C = []
| (λX.C)
| (C M )
| (M C)
| (on M . . . M C M . . . M )
The definition implies that if M 'v N , then evalv (C[M ]) and evalv (C[N ]) must be either both
defined or both undefined for any given C.
Observational equivalence obviously extends program equivalence in terms of evalv ; if pro-
grams M and N are observationally equivalent, then they are programs in the empty context, so
evalv (M ) = evalv (N ). But this is also the least we should expect from a theory of expressions
with equivalent functionality. As the name already indicates, observational equivalence is an
equivalence relation. Finally, if two expressions are observationally equivalent, then embedding
the expressions in contexts should yield observationally equivalent expressions. After all, the
added pieces are identical and should not affect the possible effects of the expressions on the
output of a program. In short, observational equivalence is a congruence relation, i.e., its
closure over contexts is also an equivalence relation.
Theorem 5.8: For any expressions M , N , and L,
1. M 'v M ;
2. if L 'v M and M 'v N , then L 'v N ;
3. if L 'v M , then M 'v L; and
4. if M 'v N , then C[M ] 'v C[N ] for all contexts C.
Proof for Theorem 5.8: Points 1 through 3 are trivial. As for point 4, assume
M 'v N and let C 0 be an arbitrary context. Then, C 0 [C] is a context for M and
N . By assumption M 'v N and therefore,
It turns out that observational equivalence is the largest congruence relation on expressions
that satistifies our intutitive criteria.
Theorem 5.9: Let R be a congruence relation such that M R N for expression M
and N implies evalv (M ) = evalv (N ). If M R N , then M 'v N .
5.7 History 51
The proposition shows that observational equivalence is the most basic, the most fundamental
congruence relation on expressions. All other relations only approximate the accuracy with
which observational equivalence identifies expressions. It also follows from the proposition that
ISWIM is sound with respect to observational equivalence. Unfortunately, it is also incomplete;
the calculus cannot prove all observational equivalence relations.
Theorem 5.10 [Soundness, Incompleteness]: If we can show M =v N , then
M 'v N . But M 'v N does not imply that we can prove M =v N .
To complete the proof of the Incompleteness Theorem, we still lack some tools. We will return
to the proof in the next chapter, when we have developed some basic more knowledge about
ISWIM.
Exercise 5.6. Consider the following evaluation function eval0 , plus its associated observa-
tional equivalence relation '0 :
Does M '0 N imply anything about M 'v N ? Sketch an argument for your answer.
5.7 History
In a series of papers in the mid-1960’s [5], Landin expounded two important observations about
programming languages. First, he argued that all programming languages share a basic set
of facilities for specifying computation but differ in their choice of data and data primitives.
The set of common facilities contains names, procedures, applications, exception mechanisms,
mutable data structures, and possibly other forms of non-local control. Languages for numerical
applications typically include several forms of numerical constants and large sets of numerical
primitives, while those for string manipulation typically offer efficient string matching and
manipulation primitives.
Second, he urged that programmers and implementors alike should think of a programming
language as an advanced, symbolic form of arithmetic and algebra. Since all of us are used
to calculating with numbers, booleans, and even more complex data structures from our days
in kindergarten and high school, it should be easy to calculate with programs, too. Program
evaluation, many forms of program editing, program transformations, and optimizations are
just different, more elaborate forms of calculation. Instead of simple arithmetic expressions,
such calculations deal with programs and pieces of programs.
Landin defined the programming language ISWIM. The basis of his design was Church’s
λ-calculus — a natural starting point, given Landin’s insight on the central role of procedures
52 Chapter 5: ISWIM
as a facility common to all languages. However, to support basic data and related primitives as
well as assignments and control constructs, Landin extended the λ-calculus with appropriate
constructions. He specified the semantics of the extended language with an abstract machine
because he did not know how to extend the equational theory of the λ-calculus to a theory for
the complete programming language. Indeed, it turned out that the λ-calculus does not even
explain the semantics of the pure functional sub-language because ISWIM always evaluates
the arguments to a procedure. Thus, Landin did not accomplish what he had set out to do,
namely, to define the idealized core of all programming languages and an equational calculus
that defines its semantics.
Starting with Plotkin’s work on the relationship of abstract machines to equational calculi
in the mid-1970’s [7], the gap in Landin’s work has been filled by a number of researchers,
including Felleisen, Mason, Talcott, and their collaborators. Plotkin’s work covered the ba-
sic functional sub-language of ISWIM, which requires the definition of a call-by-value variant
of the λ-calculus. Felleisen and his co-workers extended the equational theory with axioms
that account for several distinct kinds of imperative language facilities. Mason and Talcott
investigated the use of equational theories for full ISWIM-like languages as a tool for program
verification and transformational programming.
Although ISWIM did not become an actively used language, the philosophy of ISWIM lives
on in modern programming languages, most notably, Scheme and ML, and its approach to
language analysis and design applies to basically all programming languages. And one goal of
this book is to illustrate the design, analysis and use of equational theories like the λ-calculus
in the context of programming language design and analysis.
53
The definition of the ISWIM evaluator via an equational proof system is elegant and flexible.
A programmer can liberally apply the rules of the equational system in any order and at any
place in the program, pursuing any strategy for such a calculation that seems profitable, then
switching as soon as a different one appears to yield better results. For example, in cases
involving the fixed point operator, the right-to-left direction of the βv -axiom is useful, whereas
in other cases the opposite direction is preferable. However, this flexibility of the calculus is
clearly not a good basis for implementing the evaluator evalv as a computer program. Since
we know from the Church-Rosser Theorem that a program is equal to a value precisely when
it reduces to a value, we already know that we can rely on reductions in the search for a result.
But even the restriction to reductions is not completely satisfactory because there are still too
many redexes to choose from. An implementation would clearly benefit from knowing that
picking a certain reduction step out of the set of possible steps guaranteed progress; otherwise,
it would have to search too many different reduction paths.
The solution is to find a strategy that reduces a program to an answer if an answer is possible.
In other words, given a program, it is possible to pick a redex according to a fixed strategy
such that the reduction of the redex brings the evaluation one step closer to the result. The
strategy is known as Curry-Feys Standardization. The strategy and its correctness theorem,
the Curry-Feys Standard Reduction Theorem, are the subject of the first section.
The standard reduction strategy essentially defines a textual machine for ISWIM. In
contrast to a real computer, the states of a textual machine are programs, and the machine
instructions transform programs into programs. Nevertheless, the textual machine provides the
foundation for a first implementation of the evaluator. As we will see in the next chapter, a
systematic elimination of its inefficiencies and overlaps leads to machines with more efficient
representations of intermediate states, and every step in this development is easy to justify and
to formalize.
Another use of the textual machine concerns the analysis of the behavior of programs. For
example, all program evaluations either end in a value, continue for ever, or reach a stuck state
due to the misapplication of a primitive. Similarly, if a closed sub-expression plays a role during
the evaluation, it must become the “current” instruction at some point during the evaluation.
In the latter sections of this chapter, we prove theorems that formalize such properties.
Both underlined sub-expressions are redexes. By reducing the larger one, the evaluation process
clearly makes progress. After the reduction the new program is
((λy.y) d 7e ),
which is one reduction step away from the result, d 7e . However, if the evaluator were to choose
the inner redex and were to continue in this way, it would not find the result of the program:
((λxy.y) (λx.((λz.z z z) (λz.z z z))) d 7e )
→v ((λxy.y) (λx.((λz.z z z) (λz.z z z) (λz.z z z)))) d 7e )
→v ((λxy.y) (λx.((λz.z z z) (λz.z z z) (λz.z z z) (λz.z z z)))) d 7e )
→v ...
54 Chapter 6: Standard Reduction
The problem with the second strategy is obvious: it does not find the result of the program
because it reduces sub-expressions inside of λ-abstractions, and leaves the outer applications
of the program intact. This observation also hints at a simple solution. A good evaluation
strategy based on reductions should only pick redexes that are outside of abstractions. We
make this more precise with a set of two rules:
1. If the expression is an application and all components are values, then, if the expression
is a redex, it is the next redex to be reduced; if not, the program cannot have a value.
2. If the expression is an application but does not only consist of values, then pick one of
the non-values and search for a potential redex in it.
The second rule is ambiguous because it permits distinct sub-expressions of a program to be
candidates for further reduction. Since a deterministic strategy should pick a unique sub-
expression as a candidate for further reduction, we arbitrarily choose to search for redexes in
such an application from left to right:
20 . If the program is an application such that at least one of its sub-expressions is not a value,
pick the leftmost non-value and search for a redex in there.
By following the above algorithm, we divide a program into an application consisting of values
and a context. The shape of such a context is determined by our rules: it is either a hole,
or it is an application and the sub-context is to the right of all values. Since these contexts
play a special role in our subsequent investigations, we provide a formal definition for the set
of evaluation contexts E.
E = []
| (V E)
| (E M )
| (on V . . . V E M . . . M )
To verify that our informal strategy picks a unique sub-expression from a program as a potential
redex, we show that every program is either a value, or it is a unique evaluation context filled
with an application that solely consists of values.
Proof for Theorem 6.1: By induction on the structure of M . The base cases
hold because they are values. Similarly, the (λX.N ) case holds because it is a value.
Otherwise, M is an operator application or function application.
Assume that M = (on N1 . . . Nn ). If all Ni ∈ V , we are done. Otherwise there is a
leftmost argument expression Ni (where 1 ≤ i ≤ n) that is not a value. By induction,
Ni can be partitioned into a unique evaluation context E 0 and some application L.
Then E = (on N1 . . . Ni−1 E 0 Ni+1 . . . Nn ) is an evaluation context, and M = E[L].
The context is unique since i is the minimal index such that N1 , . . . Ni−1 ∈ V and
E 0 was unique by induction.
The case for function applications is analogous.
It follows from Theorem 6.1 that if M = E[L] where L is an application consisting of values,
then L is uniquely determined. If L is moreover a βv or a δ redex, it is the redex that, according
to our intuitive rules 1 and 20 , must be reduced. Reducing it produces a new program, which
can be decomposed again. In short, to get an answer for a program: if it is a value, there
6.1 Standard Reductions 55
is nothing to do, otherwise decompose the program into an evaluation context and a redex,
reduce the redex, and start over. To formalize this idea, we introduce a standard reduction
relation 7−→v .
The separate values V and U are needed in the theorem’s statement because a → →v reduction
might reduce expressions within a λ-abstraction. From the perspective of an evaluator, such
reductions are useless, because they do not change the result function. We defer the proof of
the theorem until the next section.
The alternative evalvs function maps a program to its value using the standard reduction
relation 7−→
→v , if a value exists.
b if M 7−→
→v b
evalvs (M ) =
function if M 7−→
→v λX.N
It is a simple corollary of Theorem 6.2 that this new evaluator function is the same as the
original one.
(+ ((λx.(λy.y) x) (− d 2e d 1e )) d 8e )
to a value with 7−→v . For each step, identify the evaluation context.
Exercise 6.2. Suppose that we try to strengthen the evaluation function as follows:
b if M 7−→→v b
eval1s (M ) = function1 if M −
7 →→v λX.N N 6= λY.N 0 for any Y, N 0
function+ if M −7 →
→v λX.λY.N
M = M0 →v M1 →v . . . →v Mm = U.
For m = 0 the claim vacuously holds, but when m > 0 the claim is impossible to prove by
the simple-minded induction. While the inductive hypothesis says that for M1 → →v U there
exists a value V such that M1 7−→ →v V , it is obvious that for many pairs M0 , M1 it is not the
case that M0 7−→ →v M1 . For example, the reduction step from M0 to M1 could be inside of a
λ-abstraction, and the abstraction may be a part of the final answer.
The (mathematical) solution to this problem is to generalize the inductive hypothesis and
the theorem. Instead of proving that programs reduce to values if and only if they reduce to
values via the transitive closure of the standard reduction function, we prove that there is a
canonical sequence of reduction steps for all reductions.
To state and prove the general theorem, we introduce the notion of a standard reduction
sequence, R. A standard reduction sequence generalizes the idea of a sequence of expressions
that are related via the standard reduction function. In standard reduction sequences an
expression can relate to its successor if a sub-expression in a λ-abstraction standard reduces to
another expression. Similarly, standard reduction sequences also permit incomplete reductions,
i.e., sequences that may not reduce a redex inside of holes of evaluation context for the rest of
the sequence.
• b⊂R
• X⊂R
• If M1 . . . Mm ∈ R, then
(λX.M1 ) . . . (λX.Mm ) ∈ R
• If M1 . . . Mm ∈ R and N1 . . . Nn ∈ R, then
(M1 N1 ) . . . (Mm N1 ) (Mm N2 ) . . . (Mm Nn ) ∈ R
• If Mi,1 . . . Mi,ni ∈ R for 1 ≤ i ≤ m and ni ≥ 1, then
Clearly, the standard reduction sequences consisting of a single term are all ISWIM expressions.
We can now formulate the claim that is provable using a reasonably simple induction argu-
ment. The general idea for such a theorem is due to Curry and Feys, who proved it for Church’s
pure λ-calculus. The theorem for ISWIM is due to Plotkin.
6.2 Proving the Standard Reduction Theorem 57
Proof for Theorem 6.4: From right to left, the claim is a consequence of the
fact that if K precedes L in a standard reduction sequence, then K reduces to L.
This property clearly follows from the definition.
To prove the left-to-right direction, assume M → →v N . By the definition of →
→v ,
this means that there exist expressions M1 , . . . Mm such that
M →v M1 →v . . . Mm →v N
The critical idea is now the following: since the parallel reduction relation extends
the one-step relation, it is also true that
The proof of the main lemma relies on a size function | | for derivations of parallel reductions,
that is, the argument that two terms are in the parallel reduction relation. The size of such
derivations is approximately the number of v-redexes that an ordinary reduction between terms
would have had to perform.
Proof for Lemma 6.5: By lexicographic induction on the length n of the given
standard reduction sequence, the size of the derivation M ,→v N , and the structure
of M . It proceeds by case analysis on the last step in the derivation of M ,→v N :
• Case M = N
This case is trivial.
• Case M = (om b1 . . . bm ), N = δ(om , b1 , . . . bm )
A δ-step that transforms the outermost application is also a standard reduction
step. By combining this with the standard reduction sequence from N to Nn
yields the required standard reduction sequence from M to Nn .
58 Chapter 6: Standard Reduction
Lemma 6.6: If M ,→v N and N 7−→v L, then there exists an expression N ∗ such
→v N ∗ and N ∗ ,→v L.
that M 7−→
Proof for Lemma 6.6: By lexicographic induction on the size of the derivation
of M ,→v N and the structure of M . It proceeds by case analysis on the last step
in the parallel reduction derivation.
6.2 Proving the Standard Reduction Theorem 59
• Case M = N
In this case, the conclusion vacuously holds.
• Case M = (om b1 . . . bm ), N = δ(om , b1 , . . . bm )
Since the result of a δ-step is a value, it is impossible that N standard reduces
to some other term.
• Case M = ((λX.K) U ), N = L[X ← V ], K ,→v L, U ,→v V
M is also a βv -redex, and therefore M 7−→v K[X ← U ]. Next, by Lemma 5.7
and the derivation of this parallel reduction is smaller than the derivation of
M ,→v N by Lemma 6.8. By induction hypothesis, there must be an expression
N ∗ such that K[X ← U ] 7−→v N ∗ ,→v L[X ← V ]. Hence we can prove the
desired conclusion as follows:
(M 0 M 00 ) 7 →
− →v ((λX.K) M 00 )
7−→ →v ((λX.K) N ∗∗ )
7−→v K[X ← N ∗∗ ]
,→v K 0 [X ← N 00 ],
M 0 7−→
→v N1∗ ,→v E[K 0 ],
(M 0 M 00 ) 7−→
→v (N1∗ M 00 ) ,→v (E[K 0 ] N 00 ).
Since M 0 may not be a value, we apply the following lemma to get a value
N1∗ such that
M 0 7−→
→v N1∗ ,→v N 0 .
Putting it all together we get,
(M 0 M 00 ) 7−→ →v (N1∗ M 00 )
7−→→v (N1∗ N2∗ )
7−→v (N1∗ N2∗ )
,→v (N 0 E[K 0 ]).
Proof for Lemma 6.7: Both implications follow from an induction argument on
the size of the derivation for the parallel reduction in the antecedent.
By Lemma 6.8, we also know that the latter derivation is shorter than the
original parallel reduction step and therefore, by inductive hypothesis, there
exists an expression (λX.L) such that
2. Again, the only two parallel reductions that can transfrom a redex in the
shape of an application into a constant or variable are δ and the βv (parallel)
reductions. Thus the argument proceeds as for the first part.
Lemma 6.8: If M ,→v N has size sM and U ,→v V has size sN then (i) M [X ←
U ] ,→v N [X ← V ] and (ii) size s of the derivation of the latter is less than or equal
to sM + #(x, N ) × sU .
6.2 Proving the Standard Reduction Theorem 61
– Case M = b
M [X ← U ] = b ,→v b = M [X ← V ];
size: s = 0;
– Case M = X
M [X ← U ] = U ,→v V = M [X ← V ];
size: s = sU = #(x, M ) × sU ;
– Case M = Y 6= X
M [X ← U ] = y ,→v y = M [X ← V ];
size: s = 0;
– Case M = (λY.K)
M [X ← U ] = (λY.K[X ← U )] ,→v (λY.K[X ← V ) =]M [X ← V ] by
induction hypothesis for K ;
size: s = #(x, K) × sU = #(x, M ) × sU ;
– Case M = (K L)
M [X ← U ] = (K[X ← U ] L[X ← U )] ,→v (K[X ← V ] L[X ← V ) =
]M [X ← V ] by induction hypothesis for K , L;
size: s = #(x, K) × sU + #(x, L) × sU = #(x, M ) × sU .
• Case M = (om b1 . . . bm ), N = δ(om , b1 , . . . bm )
Here, M and N are closed, so M [X ← U ] = M , N [X ← V ] = N , and the
result follows directly from the assumption.
Size: s = 0.
• Case M = ((λy.K) W ), N = L[y ← W 0 ], K ,→v L, W ,→v W 0
A simple calculation shows that the claim holds:
M [X ← U ] = ((λy.K[X ← U )] W [X ← U )]
,→v L[X ← V ][X ← W 0 y[] ← V ]
= L[y ← W 0 ][X ← V ] (†)
= N [X ← V ]
Equation (†) follows from a simple induction on the structure of L.
The size of the derivation is calculated as follows. Let us assume the following
conventions about sizes:
sK : K ,→v L
s0K : K[X ← U ] ,→v L[X ← V ]
sW : W ,→v W 0
s0W : W [X ← U ] ,→v W 0 [X ← V ]
62 Chapter 6: Standard Reduction
By induction hypothesis,
s0K ≤ sK + #(x, L) × sU
s0W ≤ sW + #(x, W 0 ) × sU
M [X ← U ] = (M1 [X ← U ] M2 [X ← U )]
,→v (N1 [X ← V ] N2 [X ← V )]
= (N1 N2 )[X ← V ]
= N [X ← V ]
si : Mi ,→v Ni
s0i : Mi [X ← U ] ,→v Ni [X ← V ]
s0i ≤ si + #(x, Ni ) × sU .
s = s01 + s02
≤ s1 + #(x, N1 ) × sU + s2 + #(x, N2 ) × sU
= s1 + s2 + (#(x, N1 ) + #(x, N2 )) × sU
= sM + #(x, N ) × sU
These are all possible cases and we have thus finished the proof.
The reward of proving the standard reduction theorem is a proof of Theorem 6.2, the correctness
proof for the textual machine.
6.3 Observational Equivalence 63
Theorem 6.2: M →
→v U if and only if M 7−→
→v V for some value V and V →
→v U .
In particular, if U ∈ b then M →
→v U if and only if M 7−→
→v U .
Proof for Theorem 6.2: To prove the left to right direction, assume that
M→
→v U
and that M is not a value. It follows from Theorem 6.5 that there exists a standard
reduction sequence L1 . . . Lp such that M = L1 and Lp = U . By induction on the
length of the sequence, there exists an index i such that Li is the first value in the
sequence and
M = L1 7−→→v Li .
Set V = Li ; trivially, Li →
→v U . Moreover, constants can only be the end of a stan-
dard reduction sequence of values if the standard reduction sequence is a singleton.
Hence, the second part of the theorem concerning basic constants obviously holds.
In summary, we have shown that the specification of the evaluation function based on the
equational system is equivalent to an evaluator based on the standard reduction function. Since
the latter is a truly algorithmic specification, we can now implement the evaluator easily.
Lemma 6.9 [Activity]: If M is a closed expression and evalv (C[M ]) exists, then
(i) either evalv (C[M 0 ]) exists for all closed expressions M 0 that are of the same
kind as M ; or
(ii) for all closed expressions M 0 that are of the same kind as M , there is some
evaluation context E such that
(a) if M is an application, then
C[M 0 ] 7−→
→v E[M 0 ]
C[M 0 ] 7−→
→v E[(M 0 U )]
C[M 0 ] 7−→
→v E[(o b1 . . . M 0 . . . bn )]
Proof for Lemma 6.9: Intuitively, the proof proceeds by induction on the number
of standard reduction steps in the reduction:
C[M ] 7−→
→v V
The formulation of an appropriate induction hypothesis for the Activity Lemma requires the
notion of a multi-hole context.
C = [ ]n
| M
| (λx.C)
| (C C)
| (on C . . . C)
A multi-hole context with m holes is well-formed if each hole [ ]i has a distinct label i ∈ [1, m].
The notation C[M1 , . . . Mn ] means the expression generated by replacing each [ ]i in C with Mi .
The stronger version of Lemma 6.9 re-states the claim for m expressions and contexts with
m holes.
Lemma 6.10: If M1 , . . . Mm are closed expressions, C is a context with m holes,
and evalv (C[M1 , . . . Mm ]) exists, then
(i) either evalv (C[M10 , . . . Mm
0
]) for all closed expressions M10 , . . . Mm
0
that are of
the same kind as M1 , . . . Mm , respectively; or
(ii) for all closed expressions M10 , . . . Mm
0
that are of the same kind as M1 , . . . Mm ,
respectively, there is some evaluation context E such that for some i ∈ [1, m],
(a) if Mi is an application, then
C[M10 , . . . Mm
0
→v E[Mi0 ]
] 7−→
C[M10 , . . . Mm
0
→v E[(Mi0 U )]
] 7−→
C[M10 , . . . Mm
0
→v E[(o b1 . . . M 0 . . . bm )]
] 7−→
Proof for Lemma 6.10: The proof is an induction on the number of standard
reduction steps for the original program. If C[M1 , . . . Mm ] is a value, part (i) of the
conclusion clearly applies. Consequently, assume that
for some expression K and value V . By Theorem 6.1, the program can be partitioned
into an evaluation context E 0 and a redex (N L) such that
or into an evaluation context E 0 and a redex (on b01 . . . b0p ) such that
We deal with the first case; the proof of the second case proceeds in an analogous
manner.
1. Some expression Mi contains, or is equal to, the redex (N L). Since (N L)
is an application and E 0 an evaluation context, this is only possible if Mi is
an application. If this is the case, the first clause of part (ii) of the lemma’s
conclusion holds: for any expressions M10 , . . . Mm
0
of the correct kind,
E = C[M10 , . . . Mi−1
0 0
, [ ]i , . . . Mm ]
6.3 Observational Equivalence 65
is an evaluation context. The key to this claim is that the expressions M10 , . . .
0
Mm are of the same kind as the expressions M1 , . . . Mm , respectively. If
E 0 = E1 [(Mj E2 )]
E = C[M10 , . . . Mi−1
0 0
, [ ]i , . . . Mm ]
C[M10 , . . . Mm
0
] = E 00 [((λX.N 00 ) L0 )] 7−→v E 00 [N 00 [L0 ] ← x]
and
0
E 00 [N 00 [L0 ] ← x] = C [Mj01 , . . . Mj0q ]
The intermediate program satisfies the antecedent of our claim, the reduc-
tion
0
C [Mj1 , . . . , Mjq ] 7−→
→v V
is shorter, and therefore the induction hypothesis applies.
Equipped with the Activity Lemma, we are ready to finish Theorem 5.10 with the following
lemma. It shows the observational equivalence of two expressions that are not provably equal.
Proof for Lemma 6.11: Assume for some C that evalv (C[Ω]) exists. By the
Activity Lemma, it could be the case that for all closed expressions M there is some
evaluation context such that
C[M ] 7−→
→v E[M ]
66 Chapter 6: Standard Reduction
But this contradicts the assumption that C[Ω] exists because E[Ω] is a diverging
program. Hence, evalv (C[M ]) exists for all closed expressions M and in particular
for M = (Ω (λx.x)).
Conversely, assume that evalv (C[(Ω (λx.x))]) exists, then by an argument along the
same lines, evalv (C[Ω]) exists. Clearly, if one of the programs returns an abstraction,
then so does the other, and both return the same basic constant. In short,
such that 7−→v is undefined for Mm and Mm is not an answer. For this to be the case, Mm
must contain an application consisting of values in the hole of an evaluation contexts such that
neither the βv nor the δ reduction applies, i.e.,
Adopting a machine-oriented view, programs for which 7−→v is undefined are called stuck
states. Stuck states play an important role in the analysis of machines and other programming
language tools. A precise understanding of the stuck states of any given programming language
is therefore crucial. We first give a formal definition of ISWIM stuck states.
An application M is stuck if
1. M = (om b1 . . . bm ) and δ(om , b1 , . . . bm ) is undefined; or
2. M = (om b1 . . . bi−1 (λX.N ) bi+1 . . . bm ); or
3. M = (b V ).
A program M is stuck if M = E[N ] for some evaluation context E and a stuck application
N.
A program in pure ISWIM can only evaluate to a value, a stuck program, or diverge.
Lemma 6.12: If M is a closed expression, then either
1. M 7−→
→v V for some value V ;
2. M 7−→
→v N for some stuck program N ;
3. for all N such that M 7−→
→v N , there exists an L such that N 7−→v L.
6.4 Uniform Evaluation 67
Proof for Lemma 6.12: Assume there exists an N such that M 7−→
→v N and
7−→v is undefined for N . That is,
N = E[(U V )] or N = E[(on V1 . . . Vn )]
If the applications in the hole are redexes, we have a contradiction to our assumption.
Consequently, U is neither a λ-abstraction nor a primitive but is a basic constant.
Similarly, some Vi must not be a basic constant or δ(on , V1 , . . . Vn ) is not defined.
Hence, N is a stuck program. In conclusion, programs either diverge, or reduce to
a value or to a stuck state.
Chapter 7: Machines
Every evaluation cycle in the standard-reduction textual machine performs three steps:
1. It tests whether the program is a value; if so, the machine stops.
2. If the program is an application, the machine partitions the program into an evaluation
context, E, and an application, (U V ) or (on V1 . . . Vn ).
3. If the application is a βv or δ redex, the machine constructs the contractum M and fills
the evalutaion context E with the contractum M .
The result of such a step is the program E[M ], which is the next machine state. Now the
evaluation cycle starts over.
An obvious inefficiency in this machine is the repeated partitioning of a program into an
evaluation context and a redex. Clearly, the evaluation context of the (n + 1)st step is often
the same as, or at least, is closely related to the one for the nth step. For example, consider
the evaluation of
(add1 ((λx.((λy.((λz.x) d 3e )) d 2e )) d 1e ))
which is a fairly typical example:
(add1 ((λx.((λy.((λz.x) d 3e )) d 2e )) d 1e ))
7−→v (add1 ((λy.((λz.d 1e ) d 3e )) d 2e ))
7−→v (add1 ((λz.d 1e ) d 3e ))
7−→v (add1 d 1e )
d
7−→v 2e .
The redexes in each intermediate state are underlined, the evaluation context is the part of the
term that is not underlined. The evaluation context for the first three states is (add1 [ ]). But
the machine has to recompute the evaluation context at every stage.
Depending on the use of the standard-reduction machine, the efficiency may not be an issue.
For example, if the goal of the machine is simply to formally define evalvs , then efficiency is of
no interest. However, if we want to explain an implementation of a language to others, then
we may want to formalize a more “realistic” definition of the language. In particular, no real
implementation of an ISWIM-like language would find the context from scratch on each step.
7.1 CC Machine
To eliminate repeated context computations, we can separate program states into the “current
subterm of interest” and the “current evaluation context.” Putting the former into the hole of
the latter yields the complete program. We will refer to the term of interest as the control
string M and the evaluation context simply as the context E. These two elements are paired
together to form the machine’s state: hM, Ei. The machine is called the CC machine.
In addition to the reduction tasks of the textual machine, the CC machine is responsible for
finding the redex. Initially, the entire program is the control string, and the initial evaluation
context is the empty context. The machine’s search instructions implement rules 1 and 20 from
the beginning of the previous chapter. That is, if the control string is not an application that
consists of values, the leftmost non-value becomes the control string, and the rest becomes a
part of the evaluation context.
For example, if the control string is ((K L) N ) and the evaluation context is E, then the
machine must search for the redex in (K L), and it must remember the shape of the rest of the
70 Chapter 7: Machines
program. Consequently the next state of the machine must have (K L) as the control string
component and must refine the current context E to a context of the shape E[([ ] N )]. In other
words, the CC machine must have a state transition of the form
The result of such a transition can be a state that pairs a value with an evaluation contexts.
In the textual machine, this corresponds to a step of the form E[L] 7−→v E[V ]. The textual
machine would actually divide E[V ] into a new redex L0 and a new evaluation context E 0
that is distinct from E. But the textual machine clearly does not pick random pieces from
the evaluation context to form the next redex. If E = E ∗ [((λX.M ) [ ])], then E 0 = E ∗ and
L0 = ((λX.M ) V ). That is, the new redex is formed of the innermost application in E, and E 0
is the rest of E.
Thus, for a faithful simulation of the textual machine, the CC machine needs a set of
instructions that exploit the information surrounding the hole of the context when the control
string is a value. In the running example, the CC machine would have to make a transition
from
hV, E ∗ [((λX.M ) [ ])]i
to
h((λX.M ) V ), E ∗ i
At this point, the control string is an application again, and the search process can start over.
Putting it all together, the evaluation process on a CC machine consists of shifting pieces
of the control string into the evaluation context such that the control string becomes a redex.
Once the control string has turned into a redex, an ordinary contraction occurs. If the result is
a value, the machine must shift pieces of the evaluation context back to the control string.
The 7−→cc reduction relation on CC machine states is defined as follows:
b if hM, [ ]i 7−→
→cc hb, [ ]i
evalcc (M ) =
function if hM, [ ]i 7−→
→cc hλX.N, [ ]i
By the derivation of the CC machine, it is almost obvious that it faithfully implements the
textual machine. Since evaluation on both machines is defined as a partial function from
7.1 CC Machine 71
programs to answers, a formal justification for this claim must show that the two functions are
identical.
Theorem 7.1: evalcc = evalvs .
Proof for Theorem 7.1: We need to show that if evalcc (M ) = A then evalvs (M ) =
A and vice versa. By the definition of the two evaluation functions, this requires a
proof that
M 7−→
→v V if and only if hM, [ ]i 7−→
→cc hV, [ ]i.
A natural approach to the proof of this claim is an induction of the length of the given
transition sequence. However, since intermediate states have non-empty evaluation
contexts, we will need a slightly stronger induction hypothesis:
E[M ] 7−→
→v V if and only if hM, Ei 7−→
→cc hV, [ ]i.
The hypothesis clearly implies the general theorem. Thus the rest of the proof is
a proof of this intermediate claim. The proof for each direction is an induction on
the length of the reduction sequence.
To prove the left-to-right direction of the claim, assume E[M ] 7−→
→v V . If the re-
duction sequence is empty, the conclusion is immediate, so assume there is at least
one step:
E[M ] 7−→v E 0 [N ] 7−→
→v V
where LvN for some application expression L where E 0 [L] = E[M ]. By the induc-
tive hypothesis, hN, E 0 i 7−→
→cc hV, [ ]i. To conclude the proof, we must show that
→cc hN, E 0 i
hM, Ei 7−→
If L is inside M (or the same), then E 0 must be an extension of E (or the same).
Otherwise, M must be a value, because it is inside the redex and also in an evalaution
position. Thus, depending on the shape of M and E, there are four possibilities:
• Case M = E 00 [L]
Then, E 0 = E[E 00 ]. By Lemma 7.2 below, hM, Ei 7−→ →cc hL, E[E 00 ]i and, hence,
00
→cc hN, E[E 00 ]i.
by a [ccδ] or [ccβv ] transition, hL, E[E ]i 7−→
• Case E = E 0 [((λX.N 0 ) [ ])], M ∈ V
A first step puts the redex into the control position, which enables a [ccβv ]
reduction:
hM, E 0 [((λX.N 0 ) [ ])]i 7 →cc
− h((λX.N 0 ) M ), E 0 i
7−→cc hN 0 [X ← M ], E 0 i
Since the assumptions imply that N = N 0 [X ← M ], this proves the conclusion.
• Case E = E 00 [([ ] K)], M ∈ V
Depending on the nature of K, there are two different scenarios:
1. If K ∈ V then L = (M K), which implies the conclusion.
2. If K 6∈ V then there exists an evaluation context E 000 such that K = E 000 [L].
Hence, E 0 = E 00 [(M E 000 [L])] and
hM, E 00 [([ ] K)]i 7−→cc h(M K), E 00 i
7−→cc hK, E 00 [(M [ ])]i
7−→ →cc hL, E 00 [(M E 000 )]i by Lemma 7.2
7−→ →cc hN, E 00 [(M E 000 )]i
= hN, E 0 i.
72 Chapter 7: Machines
At this point, the CC machine is forced to construct an application such that one of the
application rules can put the second application in the control string register:
. . . 7−→cc h((λx.x) d 5e ), [ ]i
7−→cc hd 5e , [ ]i.
The next to last step is only needed because the CC machine only exploits information in the
control string position. One way to simplify the CC machine is to combine the rules for values
with the reduction of redexes such that the last two steps become one step.
A similar simplification is possible when the value returned belongs into the function posi-
tion. A simple variation of the first example shows how the machine again moves information
into the control string even though the next step is clear:
h(((λx.x) (λx.x)) ((λx.x) d 5e )), [ ]i 7 →cc
− h((λx.x) (λx.x)), ([ ] ((λx.x) d 5e ))i
7−→cc h(λx.x), ([ ] ((λx.x) d 5e ))i.
Now the machine constructs an application only to move on to the evaluation of the argument
expression:
7−→cc h((λx.x) ((λx.x) d 5e )), [ ]i
7−→cc h((λx.x) d 5e ), ((λx.x) [ ])i
...
Instead of constructing the application, the machine could always put the argument into the
control register and put the value for the function position into the evaluation context. If the
argument is a value, the modified machine can perform a reduction. If not, the current CC
machine would have reached this state, too.
Once we have a machine that combines the recognition of a value with the reduction of a
redex, when possible, we can also omit the specialized treatment of applications. The current CC
machine has three distinct transitions for dealing with applications and three more for dealing
with primitive applications. Side-conditions ensure that only one transition applies to any given
application. These separate rules are only necessary because the machine performs all the work
on the control string and uses the control stack only as a simple memory. Together with the
perviously suggested simplifications, we can eliminate the side-conditions, the reduction rules,
and the rule [cc2], which only exists to move arguments from evaluation contexts into the control
string position.
The simplified CC machine has fewer transitions and no side-conditions. Given a state
finding the applicable transition rule is easy. If the control string is an application, shift a
fixed portion to the evaluation context and concentrate on one sub-expression. If it is a value,
check the innermost application of the evaluation context. If the hole is in the last position
of the application, perform a reduction, otherwise swap information between the control string
register and the evaluation context register.
b if hM, [ ]i 7−→
→scc hb, [ ]i
evalscc (M ) =
function if hM, [ ]i 7−→
→scc hλX.N, [ ]i
74 Chapter 7: Machines
The CC machine and the simplified version define the same evaluation function.
Theorem 7.3: evalscc = evalcc .
Proof for Theorem 7.3: The proof of this theorem is analoguous to the proof of
Theorem 7.1. That is, unfolding the definition of the two evaluation functions leads
to the proof obligation that
hM, [ ]i 7−→
→cc hV, [ ]i if and only if hM, [ ]i 7−→
→scc hV, [ ]i.
hM, Ei 7−→
→cc hV, [ ]i if and only if hM, Ei 7−→
→scc hV, [ ]i.
The key idea for the proof of the intermediate claim is that for any given program,
the CC machine and the SCC machine quickly synchronize at some state provided
the initial state leads to a result. More precisely, given hM, Ei such that E[M ] =
E 0 [L] and L is a v-redex, there exists a state hN, E 00 i such that
00 00
hM, Ei 7−→+
cc hN, E i and hM, Ei 7−→+
scc hN, E i
hE 0 [L], Ei 7−→
→cc hL, E[E 0 ]i 7−→cc hN, E[E 0 ]i
The SCC machine eventually reaches the same state, but the intermediate
states depend on the shape of the redex L. If L = ((λX.L0 ) L00 ), then the SCC
machine reaches hL00 , E[E 0 [((λX.L0 ) [ ])]]i as the next to last state; otherwise,
the next to last state is hb, E[E 0 [(on b1 . . . bi [ ])]]i where L = (on b1 . . . bi b).
• Case M ∈ V, E = E 0 [((λX.L0 ) [ ])]
In this case, the CC machine creates a redex in the control component and
reduces it:
hM, E 0 [((λX.L0 ) [ ])]i 7 →cc
− h((λX.L0 ) M ), E 0 i
7−→cc hL0 [X ← M ], E 0 i
The SCC machine avoids the first step and immediately goes into the same
state.
• Case M ∈ V, E = E 0 [([ ] N )]
If N ∈ V , the proof of this case proceeds along the lines of the second case.
Otherwise,
As in the previous case, the SCC machine reaches the final state by skiping
the intermediate state.
2. If N1 , . . . Nn is not empty but N1 , . . . Nn ∈ V , then
7.3 CK Machine
Each step of an evaluation on the CC or simplified CC machine refers to the innermost appli-
cation of the evaluation context—that is, the application that directly contains the hole. In
the case that the control string is an application, a new innermost application is created in the
context. In the case that the control string turns into a value, the next step is determined by
considering the innermost application. In short, the transitions always access the evaluation
76 Chapter 7: Machines
context from the inside and in a last-in, first-out fashion. Transition steps depend on the precise
shape of the first element but not on the rest of the data structure.
The observation suggests that the evaluation context register should be a list of applications
with a hole, so that the innermost part is easily accessed or added at the front of the list:
κ = κs . . .
κs = (V [ ])
| ([ ] N )
| (on V . . . V [ ] N . . .)
For readability and for ease of implementation, we tag each case of this construction and invert
the list of values in a primitive application:
κ = mt
| hfun, V, κi
| harg, N, κi
| hopd, hV, . . . , V, on i, hN, . . .i, κi
This data structure is called a continuation. The 7−→ck relation maps an expression–continuation
pair to a new expression–continuation pair.
b if hM, mti 7−→
→ck hb, mti
evalck (M ) =
function if hM, mti 7−→
→ck hλX.N, mti
Given an SCC state, we can find a corresponding CK state and vice versa, based on a bijection
between the set of evaluation contexts and the set of continuation codes:
[] if κ = mt
0
if κ = harg, N, κ0 i
E [([ ] N )]
Tck→scc (κ) =
E 0 [(V [ ])] if κ = hfun, V, κ0 i
0 n
E [(o V1 . . . Vi [ ] N . . .)] if κ = hopd, hVi , . . . V1 , on i, hN, . . .i, κ0 i
Based on this bijection between CC and CK states, it is easy to prove the correctness of the
evaluation function based on the CK machine.
Theorem 7.4: evalck = evalscc .
Proof for Theorem 7.4: Based on the translations between states, we can check
that
7.4 CEK Machine 77
1. if hM, Ei 7−→scc hN, E 0 i, then hM, Tscc→ck (E)i 7−→ck hN, Tscc→ck (E 0 )i;
2. if hM, κi 7−→ck hN, κ0 i, then hM, Tck→scc (κ)i 7−→scc hN, Tck→scc (κ0 )i.
hM, [ ]i 7−→
→scc hV, [ ]i if and only if hM, mti 7−→
→ck hV, mti,
Based these defininitions, we can reformulate the CK machine into a machine that works on
control strings with environments and continuation codes: the CEK machine. Continuations
in this machine contain closures instead of expressions.
κ = mt
| hfun, v, κi
| harg, c, κi
| hopd, hv, . . . , v, on i, hc, . . .i, κi
78 Chapter 7: Machines
The transitions are similar to CK transitions, except the expressions are replaced with closures,
and substitution is replaced by environment update.
hh(M N ), Ei, κi 7−→cek hhM, Ei, harg, hN, Ei, κii [cek1]
hh(on M N . . .), Ei, κi 7−→cek hhM, Ei, hopd, hon i, hhN, Ei, . . .i, κii [cek2]
hhV, Ei, hfun, h(λX1 .M ), E 0 i, κii 7−→cek hhM, E 0 [X1 ← hV, Ei]i, κi [cek3]
if V 6∈ X
hhV, Ei, harg, hN, E 0 i, κii 7−→cek hhN, E 0 i, hfun, hV, Ei, κii [cek4]
if V 6∈ X
hhb, Ei, 7−→cek hhV, ∅i, κi [cek5]
hopd, hhbi , Ei i, . . . hb1 , E1 i, on i, hi, κii
where δ(on , b1 , . . . , bi , b) = V
hhV, Ei, 7−→cek hhN, E 0 i, [cek6]
hopd, hv 0 , . . . on i, hhN, E 0 i, c, . . .i, κii hopd, hhV, Ei, v 0 , . . . on i, hc, . . .i, κii
if V 6∈ X
hhX, Ei, κi 7−→cek hc, κi [cek7]
where E(X) = c
b if hhM, ∅i, mti 7−→
→cek hhb, Ei, mti
evalcek (M ) =
function if hhM, ∅i, mti 7−→
→cek hhλX.N, Ei, mti
Given a CEK state, we can find a corresponding CK state with an “unload” function that
replaces every closure in the state by the closed term that it represents:
Since closures also occur inside of CEK continuation codes, the translation of CEK states into
CK states requires an additional traversal of CEK continuation codes to replace these closures:
[] if κ = mt
harg, U(c), κ∗ i if κ = harg, c, κ0 i
Tcek→ck (κ) = hfun, U(c), κ∗ i if κ = hfun, c, κ0 i
0 n ∗
hopd, hU(c ), . . . o i, hU(c), . . .i, κ i
if κ = hopd, hc0 , . . . on i, hc, . . .i, κ0 i
where κ = Tcek→ck (κ0 )
∗
Unfortunately, it is impossible to define inverses of the U and Tcek→ck functions; given a closed
term, there are many closures that map back to the same term. As a result, the simple
proof method of the preceding adequacy theorems for verifying the equality between the SCC
evaluator and the CK evaluator fails here. However, as in the preceding sections, it is still the
case that the CEK machine can simulate any given sequence of CK states if the initial state of
the two machines are equivalent.
Theorem 7.5: evalcek = evalck .
Proof for Theorem 7.5: Given the translation from CEK states, we can check
that for any intermediate state hc, κi in the sequence of CEK states, there is a state
hc0 , κ0 i such that
→cek hc0 , κ0 i
hc, κi 7−→
and
hU(c), Tcek→ck (κ)i 7−→ck hU(c0 , Tcek→ck (κ0 ))i
Hence, hhM, ∅i, mti 7−→→cek hhV, Ei, mti implies hM, mti 7−→ck hU(hV, Ei), mti, which
proves the left-to-right direction.
7.4 CEK Machine 79
The right-to-left direction requires a stronger induction hypothesis than the left-to-
right direction or the inductions of the preceding adequacy theorems because of the
lack of a function from CK states to CEK states. In addition to the intial state of
the transition sequence of the CK machine, we need to know the initial state of the
CEK machine:
For every CK state hM1 , κ1 i and CEK state hhM10 , Ei, κ01 i such that M1 =
U(hM10 , Ei) and κ1 = Tcek→ck (κ01 ), if
hM1 , κ1 i 7−→
→ck hV, mti
The theorem follows from specializing the two initial states to hM, mti and hhM, ∅i, mti.
The proof of the claim is by induction on the length of the transition sequence in
the CK machine. It proceeds by case analysis of the initial state of the CK machine:
• Case M1 = (L N )
The CK machine performs a [ck1] instruction:
hh(L0 N 0 ), Ei, κ01 i 7−→ck hhL0 , Ei, harg, hN 0 , Ei, κ01 ii.
Clearly, Tcek→ck (harg, hN 0 , Ei, κ01 i) = harg, N, κ1 i. Thus the inductive hypoth-
esis applies and proves the claim for this case.
• Case M1 ∈ V, κ1 = hfun, (λX.N ), κ2 i
Here the CK transition sequence begins as follows:
Given the definition of U, there are two kinds of CEK states that can map to
the given CK state:
– Case M10 6∈ X
In this case, the CEK step directly corresponds to the CK step:
In both cases, the assumptions state U(hM10 , Ei) = M1 . Hence, to finish the
case, we must show that
which implies
N 0 [X1 ← U(c1 )] . . . [Xn ← U(cn )] = N.
By the Substitution Lemma,
The rest follows again by induction on the length of the CK transition sequence.
The proof of the other cases are analoguous to the last one.
b if hM, [ ]i 7−→
→cc hb, [ ]i
evalcc (M ) =
function if hM, [ ]i 7−→
→cc hλX.N, [ ]i
SCC machine
h(M N ), Ei 7−→scc hM, E[([ ] N )]i [scc1]
h(on M N . . .), Ei 7−→scc hM, E[(on [ ] N . . .)]i [scc2]
hV, E[((λX.M ) [ ])]i 7−→scc hM [X ← V ], Ei [scc3]
hV, E[([ ] N )]i 7−→scc hN, E[(V [ ])]i [scc4]
hb, E[(on b1 . . . bi [ ])]i 7−→scc hV, Ei [scc5]
where δ(on , b1 , . . . , bi , b) = V
hV, E[(on V1 . . . Vi [ ] N L . . .)]i 7−→scc hN, E[(on V1 . . . Vi V [ ] L . . .)]i [scc6]
b if hM, [ ]i 7−→
→scc hb, [ ]i
evalscc (M ) =
function if hM, [ ]i 7−→
→scc hλX.N, [ ]i
CK machine
κ = mt
| hfun, V, κi
| harg, N, κi
| hopd, hV, . . . , V, on i, hN, . . .i, κi
b if hM, mti 7−→
→ck hb, mti
evalck (M ) =
function if hM, mti 7−→
→ck hλX.N, mti
82 Chapter 7: Machines
CEK Machine
E = a function {hX, ci, . . .}
c = {hM, Ei | FV(M ) ⊂ dom(E)}
v = {hV, Ei | hV, Ei ∈ c}
κ = mt
| hfun, v, κi
| harg, c, κi
| hopd, hv, . . . , v, on i, hc, . . .i, κi
hh(M N ), Ei, κi 7−→cek hhM, Ei, harg, hN, Ei, κii [cek1]
hh(on M N . . .), Ei, κi 7−→cek hhM, Ei, hopd, hon i, hhN, Ei, . . .i, κii [cek2]
hhV, Ei, hfun, h(λX1 .M ), E 0 i, κii 7−→cek hhM, E 0 [X1 ← hV, Ei]i, κi [cek3]
if V 6∈ X
hhV, Ei, harg, hN, E 0 i, κii 7−→cek hhN, E 0 i, hfun, hV, Ei, κii [cek4]
if V 6∈ X
hhb, Ei, 7−→cek hhV, ∅i, κi [cek5]
hopd, hhbi , Ei i, . . . hb1 , E1 i, on i, hi, κii
where δ(on , b1 , . . . , bi , b) = V
hhV, Ei, 7−→cek hhN, E 0 i, [cek6]
hopd, hc0 , . . . on i, hhN, E 0 i, c, . . .i, κii hopd, hhV, Ei, c0 , . . . on i, hc, . . .i, κii
if V 6∈ X
hhX, Ei, κi 7−→cek hc, κi [cek7]
where E(X) = c
b if hhM, ∅i, mti 7−→
→cek hhb, Ei, mti
evalcek (M ) =
function if hhM, ∅i, mti 7−→
→cek hhλX.N, Ei, mti
83
We derived the CEK machine by starting with the equational system =v , then refining it step-
by-step to eliminate aspects of the reduction rules that were not easily mapped to small and
efficient sequences of processor instructions. With each refinement step, we were able to prove
that the new evaluator was equivalent to the old evaluator. Consequently, evalv = evalcek , so
our theorems about the original evaluator hold for the CEK machine.
In this chapter, we consider aspects of evaluation beyond the simple result of the evalv
function. Since we are trying to work towards a realistic implmentation of ISWIM, we must
consider resource-usage issues as well as efficiency issues. For example, Ω not only loops forever,
but it does so in →v without ever growing. In other words, Ω corresponds to a Java for loop,
as opposed to a Java method that always calls itselfs. The difference is that the self-calling
Java method will eventually exhaust the stack.
To clarify this point, we embark on a slight detour: we consider a different machine formu-
lation of ISWIM, called the SECD machine, that evaluates expressions to the same result as
evalv , but which has different resource-usage properties. We then consider the implications of
the CEK machine’s resource usage for a programmer, and the implications of the mechanism.
In particular, we discuss the notion of tail calls, and of continuations as values.
Ĉ =
| b Ĉ
| X Ĉ
| ap Ĉ
| primon Ĉ
| hX, Ĉi Ĉ
[[b]]secd = b
[[X]]secd = X
[[(M1 M2 )]]secd = [[M1 ]]secd [[M2 ]]secd ap
[[(on M1 . . . Mn )]]secd = [[M1 ]]secd . . . [[Mn ]]secd primon
[[(λX.M )]]secd = hX, [[M ]]secd i
Each evaluation step for the SECD machine applies to a tuple of four elements:
In the terms of a conventional imperative language (e.g., Java, C), the Ŝ part corresponds to
the method- or procedure-local stack, and the D̂ part is the rest of the stack. The sets Ŝ, Ê,
84 Chapter 8: SECD, Tail Calls, and Safe for Space
Ŝ =
| V̂ S
Ê = a function {hX, V̂ i, . . .}
D̂ =
| hŜ, Ê, Ĉ, D̂i
V̂ = b
| hhX, Ĉi, Êi
hŜ, Ê, b Ĉ, D̂i 7−→secd hb Ŝ, Ê, Ĉ, D̂i [secd1]
hŜ, Ê, X Ĉ, D̂i 7−→secd hV̂ Ŝ, Ê, Ĉ, D̂i [secd2]
where V̂ = Ê(X)
hbn . . . b1 Ŝ, Ê, primon Ĉ, D̂i 7−→secd hV̂ Ŝ, Ê, Ĉ, D̂ii [secd3]
where V̂ = δ(on , b1 , . . . bn )
hŜ, Ê, hX, C 0 i C, Di 7−→secd hhhX, C 0 i, Êi Ŝ, Ê, Ĉ, D̂i [secd4]
hV̂ hhX, C 0 i, Ê 0 i Ŝ, Ê, ap C, Di 7 →secd
− h, Ê 0 [X ← V̂ ], C 0 , hŜ, Ê, C, Dii [secd5]
hV̂ Ŝ, Ê, ∅, hŜ 0 , Ê 0 , C 0 , Dii 7−→secd hV̂ Ŝ 0 , Ê 0 , C 0 , Di [secd6]
b if h, ∅, [[M ]]secd , i 7−→
→secd hb, Ê, , i
evalsecd (M ) =
→secd hhhX, Ĉi, Ê 0 i, Ê, , i
function if h, ∅, [[M ]]secd , i 7−→
The SECD and CEK machines produce the same result for any expression that has a result.
We will not prove this claim. For our purposes, the more interesting fact is that CEK and
SECD machines produce the same result in different ways. In particular, a programmer might
notice the difference when using a real machine with finite resources.
• In the SECD machine, context is created by function calls, where the current stack,
environment, and control are packaged into a dump. The stack provides a working area
for assembling application arguments..
This view of context accumulation is natural when approaching computation as in Java,
Pascal, or C.
• In the CEK machine, context is created when evaluating an application function or ar-
gument, regardless of whether the function or argument is a complex expression. (The
argument stack is subsumed by the continuation.) Function application always shrinks
the context, rather than expanding it.
This view of context accumulation is natural when approaching computation as in the
λ-calculus, Scheme, or ML.
8.2 Context Space 85
Due to this difference, the SECD and CEK machines behave differently on recursive programs.
As an extreme example, consider the evaluation of Ω:
(λx.x x)(λx.x x)
Both machines loop forever on this expression. However, the nature of the infinite loop is
different. The CEK machine’s state will never grow beyond a certain size while evaluating:
In contrast, the state of the SECD machine will grow in size forever:
In other words, the CEK machine evaluates Ω as a loop, while the SECD machine evaluates Ω
as infinite function recursion as in Java or C.
The notion of saving context on argument evaluations, rather than on function calls, corre-
sponds to tail calls (or tail recursion) in programming languages. For example, the following
program runs forever in Scheme, without running out of stack space:
(define (f x) (f x))
(f ’ignored)
More generally, the semantics of Scheme must be understood in terms of a CEK-like model,
and not an SECD-like model.
Of course, the relevance of tail calls extends beyond infinite loops. Since real machines
generally have a finite amount of memory, the difference between loops and stack-based recursion
is important for large (but bounded) recursions as well.
For example, every C programmer knows to implement a function that processes a long list
as a loop, instead of with recursion, to avoid overflowing the stack. In languages that support
tail calls, a recursive definition can be just as efficient as a loop. Languages such as Scheme
and ML do not even provide a looping construct, since it is unnecessary.
Exercise 8.1. Which of the following expressions loop with a bounded size in the CEK ma-
chine?
86 Chapter 8: SECD, Tail Calls, and Safe for Space
• Yv (λf.λx.f x) d 0e
• Yv (λf.λx.if0 x (f d 10e ) (f (− x d 1e ))) d 0e
• Yv (λf.λx.if0 x (f d 10e ) (− (f x) d 1e )) d 0e
Exercise 8.2. Which of the following expressions execute in the CEK machine with a bounded
size that is independent of n, for a non-negative n?
.
• Yv mkodd d ne where mkodd = λf.λx.if0 x false (not (f (− x 1)))
.
• Yv mkoe false d ne where mkoe = λf.λz.λx.if0 x z (f (not z) (− x 1))
In the closure h(λx.x), E1 i, none of the bindings in E1 are actually needed, because (λx.x)
has no free variables. In other words, substitutions were delayed and accumulated as E1 , but the
substitutions would not have affected the expression if they had been performed immediately.
If the substitions were actually needed, then reductions with 7−→v would grow, too. For
example, replacing F in the example with (λf.(λx.((f f ) (λy.x)))) leads to an infinitely growing
state with both 7−→v and 7−→cek . In that case, the x in (λy.x) is free, so an immediate substution
for x in (λy.x) changes the expression to keep the same information that is collected in E1 (and
then E3 , etc.).
In general, to repair the CEK machine and obtain the same space consumption as 7−→v , we
can change closure formation to discard unnecessary subsitions from an environment. Given an
expression M and an environment E, the closure should be hM, E 0 i where E 0 is like E, but with
its domain restricted to FV(M ). For example, closing (λx.x) with E1 should form h(λx.x), ∅i.
A machine with the same space consumption as 7−→v is called safe for space. Some
practical implementations of Scheme-like languages are not safe for space; however, practical
implementations do prune the environment when forming a closure that corresponds to a pro-
cedure value. Since recursion requires procedure closures, pruning for procedures is enough to
make tail calls effective; programs that run in constant space with 7−→v also run in constant
space in a machine that prunes only procedure-closure environments (but programs that run
in O(n) with 7−→v may, for example, run in O(n2 ) space in the same machine).
8.4 History
The SECD machine is from Landin’s original paper on ISWIM [5]. Plotkin showed that an
evaluator based on the SECD machine is equivalent to call-by-value lambda calculus [7].
Chase [3] is usually credited as the first to observe space problems when implementing
an ISWIM-like language through a CEK-like interpreter. Appel [1] formalized the notion of
safe-for-space. Clinger [4] connected the notions of tail recursion and space safety in a more
implementation-neutral formalization, similar to the connection here between 7−→v and 7−→cek .
88 Chapter 8: SECD, Tail Calls, and Safe for Space
89
Chapter 9: Continuations
The CEK machine explains how a language like ISWIM can be implemented on a realistic
machine:
• Each of three parts of state in the CEK machine (the current expression, environment,
and continuation) can be stored in a register.
• Each CEK step can be implemented with a fairly simple sequence of processor instructions.
Environment lookup has a fairly obvious implementation.
We have neglected the allocation aspects of the machine (for now), but we’ve seen that the
machine state’s size is bounded when it should be (if environments are pruned appropriately).
As we developed the machine, not only do theorems about evaluation with evalv carry over,
but the programmer’s understanding of evaluation with 7−→v is fairly intact. This is important
to our goal of decribing languages and evaluation in an understandable way.
There is, however, one “strange” aspect of the machine: the K register. The C and E
registers correspond closely to constructs in the language. The C register contains an expression,
which programmers can form at will, and the E register contains an environment, which a
programmer can capture using a λ (to form a closure). But the K register does not correspond
to anything that the programmer can write or capture within the language.
What if we add a construct to the language for capturing the current continuation? The
only use for a continuation is in the last slot of the machine, so the only useful operation a
program might perform on a continution is to use it—replacing the current continuation.
To investigate the use of continuations as values, we extend ISWIM with letcc and cc
forms:
M = ...
| (letcc X M )
| (cc M M )
The new letcc form grabs the current continuation and binds it to a variable while evalut-
ing an expression. The new cc form replaces the current continuation with the value of its
first subexpression, and supplies the value of its second subexpression to the newly restored
continuation.
M = ... V = ...
| bEc | bEc
In terms of evaluation contexts, the letcc form grabs the current context. A use of the cc
form later will restore the grabbed context, regardless of whatever might be happening at that
later point. The entire context at the later point is discarded; for example, if the evaluator was
in the process of evaluating some argument to a primitive, then we forget about the primitive
application, and everything around it, and return instead to whatever we were doing when the
context was grabbed.
Here’s a simple example use of letcc and cc:
90 Chapter 9: Continuations
(+ d 1e
(letcc x
(+ (λy.y)
(cc x d 12e ))))
In the inner addition expression, the first argument is a function. Evaluating the example
expression starts evaluating the addition expression, but before the addition can discover that
the first argument is not a number, the (cc x d 12e ) expression “jumps” out of the addition.
The result will be d 13e .
Let’s walk through it slowly. To evaluate the outside addition, we first evaluate 1 (which
has the value 1), and then consider the letcc expression. At that point, the evaluation context
is E0 and the redex is M0 :
E0 = (+ d 1e M0 = (letcc x
[]) (+ (λy.y)
(cc x d 12e )))
The letcc expression binds the context E0 to the variable x via replacement. Then the letcc
disappears, in the same way that application makes λ disappear. Thus, the entire expression
is as follows:
(+ d 1e
(+ (λy.y)
(cc bEo c d 12e ))))
Paritioning this expression produces a context E1 and redex M1 :
E1 = (+ d 1e M1 = (cc bE0 c d 12e )
(+ (λy.y)
[ ] ))
The context E1 turns out not to matter, because the cc expression throws it away and replaces
it with E0 . The cc expression also provides d 12e as the value to go into the hole of the restored
context, so the expression to evaluate becomes
(+ d 1e
d
12e )
The final result is d 13e .
The example above shows how continuations can be used to define an error-handling mech-
anism. Continuations can also be used for implementing cooperative threads (“coroutines”), or
for saving and restoring speculative computations. Some languages, notably Scheme, provide
constructs like letcc and cc. Furthermore, some Scheme implementations define the exception
mechanism in terms of continuations.
E = ...
| (cc E M )
| (cc V E)
E[M ] 7 →v
− E[M 0 ] if M v M 0
E[(letcc X M )] 7−→v E[M [X ← bEc]]
E[(cc bE 0 c V )] 7−→v E 0 [V ]
91
With these extensions, we can demonstrate formally the reduction of the example from the
previous section. The redex is underlied in each step:
κ = ...
| hccval, hM, Ei, κi
| hcc, κ, κi
V = ...
| κ
Exercise 9.2. The above extension of CEK with continuations could be more efficient with
simple changes. In particular, the κ in hcc, κ, κ0 i is never used. Suggest revisions to the κ
grammar and the 7−→cek rules to streamline the machine.
What is the value of (Z mkodd 1)? Justify your answer, but don’t try to write down a complete
CEK reduction.
What does ((callcc callcc) (callcc callcc)) do? Justify your answer.
Exercise 9.5. Is the evaluation of ((callcc callcc) (callcc callcc)) bounded in the revised CEK
92 Chapter 9: Continuations
Exercise 9.6. Is the evaluation of ((λy.((callcc callcc) y)) (callcc callcc)) bounded in the revised
CEK machine? Justify your answer.
93
An ISWIM program might diverge for two distinct reasons. First, a program’s standard reduc-
tion sequence may have a successor for every intermediate state. This situation corresponds
to a genuine infinite loop in the program, which, in general, cannot be detected. Second, a
program’s standard reduction sequence may end in a stuck state, that is, a program that is not
a value and has no successor. One typical example is the application of a division primitive to
0; another one is the use of a numeral in function position.
An interpreter that diverges when a program reaches a stuck state leaves the programmer
in the dark about the execution of his program. The interpreter should instead signal an error
that indicates the source of the trouble. One way to specify the revised interpreter for ISWIM
is to add the element err to the set of answers and to add a single clause to the definition of
the evaluator:
b if M 7−→
→v b
eval(M ) = function if M 7−→ →v λX.N
err if M 7−→
→v N and N is stuck
By Lemma 6.12, which shows that the three enumerated cases plus divergence are the only
possible ways for the evaluation of a program to proceed, we know that the extended evaluator
is still a partial function from programs to answers. However, beyond programming errors, it is
often necessary to terminate the execution of a program in a controlled manner. For example, a
program may encode an input–output process for a certain set of data but may have to accept
data from some larger set. If the input data for such a program are outside of its proper domain,
it should signal this event and terminate in a predictable manner.
In plain ISWIM, a programmer can only express the idea of signaling an error by writing
down an erroneous expression like (add1 λy.y). We would like instead a linguistic tool for
programmers to express error termination directly. We solve this problem by adding error
constructs to the syntax of ISWIM. In the extended language a programmer can explicitly
write down err with the intention that the evaluation of err terminates the execution of the
program. We treat this extended version of ISWIM in the first section of this chapter.
When a language contains constructs for signaling errors, it is also natural to add constructs
that detect whether an error occurred during the evaluation of a subprogram such that the
program can take remedial action. These exception-handling constructs are highly desirable
in practice and are provided by many programming languages. Besides handling unpreventable
errors, exception-handling can be used to exit from loops once the result has been detected,
or to implement some form of backtracking. In the second and later sections, we examine a
variety of exception handling mechanisms.
10.1 Errors
Since a program can encounter many different types of error situations, we add an undetermined
set of errors to ISWIM. Each element of this set plays the role of a syntactic construct. We
assume that the set is non-empty but make no other restrictions for now.
an error. A precise specification of the behavior of errl in terms of calculation rules requires
an analysis of how errl interacts with other syntactic constructions. Take application as an
example. If a function is applied to errl , the appliction must be terminated. We can express
this requirement with the following informal notions of reduction:
The rules clarify that errl is not an ordinary value; otherwise applications like ((λx.d 5e ) errl )
would reduce to d 5e . The case for errl in function position is similarly straightforward. When
errl occurs in function position, there is no function to be applied so the application also
reduces to errl :
(errl N ) → errl
Next we need to consider the situation when errl occurs as the body of a procedure. Since
a procedure like (λx.errl ) may never be invoked, the errl should not propagate through the
abstraction. The hidden errl should only become visible when the λ-abstraction is applied to
a value. In other words, (λx.errl ) is an irreducible value.
Given that the evaluation context surrounding a redex represents the rest of the compu-
tation, a natural formalization of the behavior of errl says that it erases evaluation contexts.
Thus, we introduce the following error reduction:
In addition to occurrences of errl in the original program, stuck expressions should now reduce
to some error value. Consider the application of some basic constant b to an arbitrary value V .
It should reduce to an error that signals that b cannot be used as a procedure, perhaps using b
as the label:
(b V ) → errb
One question is whether the generated error should also depend on the nature of V , i.e., errbV .
Suppose an application of b to U for V 6= U reduces to a distinct error, errbU . Then, if it is
also the case that V →v U , the calculus proves
errbV =v (b V ) =v (b U ) =v errbU
That is, the two distinct errors are provably equal even though they are not identical and were
assumed to be distinct. Implementations of programming languages avoid this problem by
signaling an error that only depends on the basic constant in the function position, and not on
the argument.
Following the same reasoning, an application of a primitive operation to a value other than
a constant must also reduce to an error, independent of the actual arguments. For example,
applying the addition primitive to any abstraction yields the error constant
(+ (λxy.x) 0) → err+
and
(+ (λxy.y) 0) → err+
independent of the argument.
Finally, we must consider the application of primitive operations to a bad set of basic
constants. Since the application is unique and the error message depends on the constant, we
assume that the δ function returns an appropriate error message for bad inputs to a primitive
operation. We restrict the δ reduction (as opposed to the δ function) to produce values, however,
and introduce a new δerr reduction for errors.
10.1 Errors 95
(om b1 . . . bm ) δ V if δ(om , b1 , . . . bm ) = V
e = βv ∪ δ ∪ δerr ∪ error
Ae = b ∪ {function} ∪ err
b if M =e b
evale (M ) = function if M =e λX.N
errl if M =e errl
(+ (− 4 erra ) errb )
to errl with →e . Indicate the redex (the expression related by e) for each step. Is the resulting
l unique?
Theorem 10.1 [Consistency with Errors]: The relation evale is a partial func-
tion.
The proof of this theorem has the same structure as the proof of Theorem 5.3, the corresponding
theorem for evalv . We first prove a Church-Rosser property, that is, we show that provably
equal results reduce to some common contractum. The theorem follows from Church-Rosser
property. The proof of the property relies on the fact that the diamond property holds for
the underlying reduction. The diamond property for δ and βv extended to the larger syntax
obviously holds; an adaptation of the proof for ISWIM to Error ISWIM is straightforward. But
the calculus for Error ISWIM also includes reductions that create and move errl . Fortunately,
it is possible to combine the diamond theorems for different reductions on the same language,
a method that we will use to establish the diamond property for e.
We first deal with the extension of the ISWIM calculus to the larger syntax. We define w
as the extension of v to the full set of Error ISWIM expressions.
w = δ ∪ βv
96 Chapter 10: Errors and Exceptions
f = error ∪ δerr
Unlike v or w, this notion of reduction never duplicates expressions or creates new opportunities
to reduce sub-expressions. We might therefore expect that the one-step relation satisfies the
diamond property, but, unfortunately, it does not hold. Consider the reduction from E[errl ] to
errl . If E[errl ] also reduces to E 0 [errl ] for some evaluation context E 0 , then E 0 [errl ] directly
reduces to errl . Hence it is not the one-step reduction →f but its reflexive closure →0f that
satisfies the diamond property.
Proof for Lemma 10.3: We first prove the claim for a subset of the relation: If
L →0f M and L →0f N then there exists an expression K such that M →0f K and
N →0f K. The lemma clearly follows from this claim. The proof proceeds by case
analysis of the reduction from L to M :
• Case L is faulty; M = errl
Clearly, if L is faulty and L →0f N then N is faulty. Hence, K = errl is the
desired fourth expression.
• Case L = E[errl ]; M = errl
It is easy to check that any f -reduction applied to E[errl ] yields an expression
of the shape E 0 [errl ] for some evaluation context E 0 , which implies that the
reduction error applies to N .
• Case L = M
Set K = N .
• Case L = C[L0 ], M = C[errl ], L0 f errl
If N = C 0 [L0 ] for some context C 0 , then K = C 0 [errl ] because C[L0 ] →0f C 0 [L0 ]
implies that for all N 0 , C[N 0 ] →0f C 0 [N 0 ]. Otherwise N = C 0 [errl ] by the
definition of compatibility, in which case K = M = N .
Exercise 10.2. Prove that if L is faulty and L →f N , then N is faulty and reduces to the
same error element.
Exercise 10.3. Prove that If L = E[errl ] and L →f M , then there exists an evaluation context
E 0 such that M = E 0 [errl ].
After establishing that each of the notions of reduction w and f satisfy the diamond property,
we need to show that these results can be combined. Intuitively, the combination of w and
f should have the diamond property because the two notions of reduction do not interfere
with each other. That is, if two reductions apply to a term, the redexes do not overlap and
the reduction of one redex may destroy but not otherwise affect the other redex. Technically
speaking, the two one-step reductions commute.
If we can show that the one-step relations based on w and f commute, the commutation
for their transitive closures clealry follows. However, the one-step relations do not commute.
Consider the expression
((λf.(f (f d 0e ))) (λx.(add1 (λx.x))))
10.1 Errors 97
(+ 1 (+ d 2e [ ])) ∈ E
(+ 1 (+ d 2e erra )) error erra
(+ 1 (+ d 2e erra )) e erra [] ∈ C
(+ d 1e (+ d 2e erra )) →e erra
and
(+ d 2e [ ]) ∈ E
(+ 2e erra ) error erra
d
(+ d 2e erra ) e erra (+ d 1e [ ]) ∈ C
(+ 1 (+ 2 erra )) →e (+ d 1e erra )
d e d e
Of course, we do not expect →e to be a function, so the above result is not surprising. But it
turns out that both [ ] and (+ d 1e [ ]) are in E as well as C, so there are two ways to match
E[M ] and E[N ] with M e N . Consequently, we will not define 7−→e as the closure of e over
E. To avoid non-determinism, we define 7−→e to directly propagate errors, and close in general
only over the other relations, βv , δ, and δerr :
ẽ = βv ∪ δ ∪ δerr
E[M ] 7 →e
− E[N ] if M ẽ N
E[errl ] 7−→e errl
To state the unique partitioning theorem that ensures 7−→e and evales are functions, we must
restrict the shape of redex expressions Mre to match the way 7−→e is defined.
Mre = (V V )
| (om V . . . V )
| errl
Lemma 10.6 [Unique Evaluation Contexts for Error ISWIM]: Every closed
Error ISWIM expression M is either a value, or there exists a unique evaluation
context E and a standard redex Mre such that M = E[Mre ].
10.1 Errors 99
Proof for Lemma 10.6: The proof is similar to that of Lemma 6.1.
The lemma validates that the new specification of the evaluator, evales , is a partial function.
But, we really want to know that the new evaluator function is equal to the old one and can
be used in its place. This is also true, though we will not prove it here.
Exercise 10.4. Adapt the proof of Theorem 6.5 to prove Theorem 10.7.
Exercise 10.5. If errl contains only one element, err0 , a feasible alternative for propagating
errl through applications is the following notion of reduction:
Ea = []
| (M Ea )
| (Ea M )
| (om M . . . M Ea M . . . M )
E[M ] 7 →e 0
− E[N ] if M ẽ N
Ea [errl ] −7 →e 0 errl
Demonstrate that 7−→e0 is a not function (despite the use of 7−→). Is evales 0 , defined in terms
of 7−→e0 , a function? Is evales 0 a function when errl contains at least two elements?
Proof for Theorem 10.8: For the proof of the first claim assume M =v V . Since
v interpreted on the extended language is a strict subset of e, it is clearly true that
M =e V .
For the proof of the second claim, recall that by Theorem 10.7, evale = evales .
Hence, assume M 7−→ →e V . The assumption implies V 6= errl . But then none of
the standard reduction steps from M to V can be a step based on δerr or error. We
prove this statement by induction on the length of the standard reduction sequence
from M to V :
• Case M = V
The claim holds.
100 Chapter 10: Errors and Exceptions
A similar question concerning the relationship between the two languages is whether program
transformations that are valid for ISWIM are also valid in the extended setting. Technically
speaking, we are asking whether an observational equivalence about two ISWIM expressions is
still an observational equivalence in Error ISWIM. Not surprisingly, the answer is no. Reducing
all stuck expressions to err means that all stuck expressions are provably equal, which clearly is
not true for languages like Error ISWIM. We begin with the formal definition of observational
equivalence for Error ISWIM.
The following theorem formalizes the discussed relationship between the observational equiva-
lence relations of ISWIM and Error ISWIM.
Theorem 10.9: For and M and N ,
Proof for Theorem 10.9: The first part is obvious. Any ISWIM context that
observationally separates two ISWIM expressions is also an Error ISWIM context.
For the second part, recall that
But in Error ISWIM the two expressions are clearly distinguishable with
C = ([ ] (λx.errl ) (λx.x)).
Whereas evale (C[(λf x.((f x) Ω))]) = errl , evale (C[(λf x.Ω)]) does not exist.
The proof of the theorem reveals why Error ISWIM can distinguish more ISWIM expressions
than ISWIM itself. Some expressions that used to be observationally equivalent to divergence
are now equal to errors. But this also means that the only way such expressions can be
distinguished is via programs that eventually return errors.
Theorem 10.10: If M and N are such that M 'v N and M 6'e N , then there exists
a context C over Error ISWIM such that C[M ] and C[N ] are programs and one of
the following conditions hold:
1. There exist errors errl1 and errl2 with errl1 6= errl2 and
Proof for Theorem 10.10: Let M and N be such that M 'v N and M 6'e N .
Assume, without loss of generality, that M and N can be distinguished by observing
answers distinct from errors. For example, there may exist an Error ISWIM context
C such that C[M ] and C[N ] are programs and for some basic constants bM and bN ,
Since C is an Error ISWIM context, it may contain several error elements. However,
these error elements clearly cannot play any role in the evaluation because once a
program is an evaluation context filled with some errl , the answer must be errl .
Thus, let C 0 be like C except that all occurrences of error elements are replaced by
Ω. But then, by the following lemma,
and
evale (C[N ]) = evale (C 0 [N ]) = b2 ,
which means that some ISWIM context can already observe differences between M
and N : M 6'v N . This contradiction to the assumptions of the lemma proves that
the context C cannot exist.
We have left to prove that if a program has a proper answer, occurrences of error elements in
the program can be ignored. The corresponding lemma is a version of the Activity Lemma
(Lemma 6.9) for Error ISWIM.
Lemma 10.11: Let C be an m-hole context over Error ISWIM. If evale (C[errl1 , . . . errlm ]) =
a and a 6∈ errl , then evale (C[Ω, . . . Ω]) = a.
Proof forR Theorem 10.11: By assumption, C[errl1 , . . . errlm ] 7−→ →e V for some
value V 6 errl . We will prove by induction on the length of the reduction sequence
that C[Ω, . . . Ω] reduces to a value. If the original program is a value, the claim
clearly holds. Thus, assume that for some program M ,
The standard redex Mre cannot be an error element and it cannot be a δerr redex
because both would contradict the assumption. But then Mre reduces to some
contractum N such that for some n-ary context C 0 ,
M = C 0 [errl10 , . . . errln0 ]
C[Ω, . . . Ω] 7−→e V 0
for some value V 0 . Moreover, if V was a basic constant, then V 0 = V and if V was
a λ-abstraction then so is V 0 . Hence,
Exercise 10.6. Suppose that we weaken the evaluator so that it does not distinguish result
errors:
b if M =e b
evalê (M ) = function if M =e λX.N
err if M =e errl
Exercise 10.7. Use the proof of Theorem 10.9 to show that Error ISWIM can reveal the order
in which a procedure invokes its parameters that are procedures. Hint: Separate the cases
where errl contains only err0 , and the case where errl ⊇ {errl1 , errl2 } with errl1 6= errl2 .
Exercise 10.8. Use Theorem 10.1 to prove that for any ISWIM expressions M and N , M =v N
implies M =e N .
Conclude that for all M and N , M =e N implies M 'v N . Hint: use the Church-Rosser
theorem for ISWIM, Theorem 5.4.
Also prove that M =e N implies M 'e N . Hint: compare to Theorem 5.10.
where the expression M1 is the protected body and λX.M2 is the handler. The evaluation of
such an expression starts with the body. If the body returns some value, the value becomes the
answer of the complete expression. If the evaluation of the body signals an error, the handler
is used to determine a result.
Exception handlers are useful in many situations. For example, the evaluation of an arith-
metic expression may signal a division-by-zero error or an overflow error, yet it may suffice
to return a symbolic constant infinity if this happens. Similarly, if there are two methods
for computing a result, but the first and faster one may signal an exception; a program can
attempt to compute the answer with the first method, but when an exception occurs, control
is transferred to the second method of computation.
Provided that exceptions come with additional information, the exception handler’s action
may also depend on what kind of exception occured. Indeed, this option increases the usefulness
of exception handlers dramatically, because the handler not only knows that an exception
occurred, but also what kind of exception occurred. We will assume that the exceptions are
represented as basic constants, and that the basic constant in an throw application is the
information that a handler receives.
10.2 Exceptions and Handlers 103
Handler ISWIM extends plain ISWIM with throw and catch forms:
For an illustration of the versatility of exception handlers, we consider a procedure that multi-
plies the elements of a list of numbers. A naive version of the procedure traverses the list and
multiplies the elements one by one:
.
Π = Yv (λπ. λl. (if0 (isnull l) d 1e
(∗ (car l) (π (cdr l)))))
In Handler ISWIM, the procedure can check for an occurrence of d 0e in the list and can exit
the potentially deep recursion immediately, because the result will be d 0e . Exiting can be
implemented by raising an exception that is handled by a surrounding handler:
.
Π0 = λl.(catch (Π0 l) with λx.x)
where
.
Π0 = Yv (λπ. λl. (if0 (isnull l) d e
1
(if0 (car l) (throw d 0e )
(∗ (car l) (π (cdr l)))))
In this example, signaling an exception indicates that the proper result was found, and thus
speeds up the ordinary computation.
A notion of reduction that describes the error handling component of the behavior says that if
the first sub-expression reduces to a throw expression, its basic constant becomes the argument
of the handler:
(catch (throw b) with λX.M ) → ((λX.M ) b)
No other reductions dealing with catch expressions are needed. The second notion of reduction
also points out that the hole of an evaluation context, which represents the pending computation
of a redex, cannot be inside the body of a catch expression. Otherwise, error propagation
through evaluation contexts would circumvent error handlers.
104 Chapter 10: Errors and Exceptions
The notions of reduction for error elements have the almost same shape as the ones for Error
ISWIM. The following defines the calculus for Handler ISWIM. To deal with exceptions raised
by primitive operators, we assume a bijection EM mapping members of errl to members of b,
and we change δerr accordingly. We also change the evaluation function to include information
about the basic constant raised for an escaping exception.
Ah = b ∪ {function} ∪ errb
b if M =h b
evalh (M ) = function if M =h λX.N
errb if M =h (throw b)
Proof for Theorem 10.12: The relations catch and return trivially satisfy the
diamond property. It is also straightforward to show that the proof of the dimaond
property for the notion of reduction e (but using throw instead of error) extends
to the full syntax. If the reduction based on eltn commutes with the one based on
catch and return, we have the diamond property for the full language. To prove
the commutativity of catch and return with the old reductions, there are two cases
The consistency of the calculus and the functionhood of evalh directly follow from
the diamond property according to the familiar proof strategy.
However, we do not want to extend the definition of E with (catch E with λX.M ), because
that would allow
(catch (throw b) with λx.x) → (throw b)
by throw.
The solution is to define a new kind of evaluation context, Eh . Meanwhile, unlike in ISWIM
or Error ISWIM, E contexts do not represent the entire rest of a computation relative to a
redex. Instead, they only represent rest of the computation up to the closest catch expression.
An Eh context will represent the rest of the computation, including all the pending catch
expressions.
Eh = []
| (Eh M )
| (V Eh )
| (om V1 . . . Vi−1 Eh Mi+1 . . . Mm )
| (catch Eh with λX.M )
As with Error ISWIM, we must define the standard reduction relation so that it avoids ambi-
guities due to multiple matching throw reductions. Instead of one special rule, two are needed;
one for an uncaught exception, and one within a catch expression:
Eh [M ] 7−→h Eh [N ] if M h̃ N
E[(throw b)] 7−→h (throw b)
Eh [(catch E[(throw b)] 7−→h Eh [(catch (throw b)
with λX.M )] with λX.M )]
b if M 7−→
→h b
evalhs (M ) = function if M 7−→ →h λX.N
errb if M 7−→
→h (throw b)
106 Chapter 10: Errors and Exceptions
The correctness proof of this new specification of the evaluator consists of the usual steps,
though it is more complex to show the “unique partitioning” lemma. The redex grammar Mrh
for the lemma omits throw expressions.
Mrh = (V V )
| (om V . . . V )
| (catch V with λX.M )
| (catch (throw b) with λX.M )
Lemma 10.13 [Unique Standard Contexts]: For every closed Handler ISWIM
expression M , one of the following is true for a unique Eh , E, and Mrh :
• M is a value.
• There exist a standard context Eh and a standard redex Mrh such that M =
Eh [Mrh ].
• There exists a context E such that M = E[(throw b)].
• There exist a standard context Eh and context E such that M = Eh [(catch E[(throw b)] with λX.M )].
Second, we must show that the evaluator based on the standard reduction function is equal to
the evaluator based on the calculus. We state the theorem without proof.
Theorem 10.14: evalhs = evalh
It is obvious that any ISWIM expressions that can be distinguished in Error ISWIM can also
be distinguished in Handler ISWIM. Moreover, the result of these distinguishing programs does
not have to be an error anymore. With error handlers, all error results can be turned into basic
constants.
Theorem 10.15: M 'e N implies M 'h N . Moreover, the analogue of Theo-
rem 10.10 does not hold for Handler ISWIM.
Proof for Theorem 10.15: The first part is trivial. For the second part, assume
that C is a distinguishing context in Error ISWIM for M and N . Take
C 0 = (catch C with λx.x)
as the distinguishing context in Handler ISWIM.
Conjecture 10.16: M 'h N implies M 'e N .
Conjecture 10.17: {(M, N ) | M 'v N and M 6'e N } is the same as {(M, N ) | M 'v
N and M 6'h N } .
Note: The first conjecture implies the second.
Exercise 10.9. Suppose that we weaken the evaluator so that it does not distinguish result
errors:
b if M =h b
evalĥ (M ) = function if M =h λX.N
err if M =h (throw b)
10.3 Machines for Exceptions 107
It differs from the original evaluator in that it maps all programs to basic constants or function.
In particular, the modified evaluator ignores the difference between errors and basic constants.
Check that the modified evaluator is still a function. Are the two observational equivalence
relations, defined by evalh and eval3 , the same?
b if hM, [ ]i 7−→
→cc hb, [ ]i
evalcc+h (M ) = function if hM, [ ]i 7−→
→cc hλX.N, [ ]i
errb if hM, [ ]i 7−→
→cc h(throw b), [ ]i
108 Chapter 10: Errors and Exceptions
For a proof of correctness of this machine, it suffices to check that the six new transitions
faithfully implement the five new standard reduction transitions. This check is a straightforward
exercise.
Exercise 10.12. Prove that it is possible to eliminate [cc8] by wraping the initial program in a
handler.
When the body of a catch expression is eventually reduced to a value, the machine pops the
stack
hV, [ ], hλX.N, EiHi → hV, E, Hi
that is, it throws away the current handler and reinstalls the surrounding evaluation context.
The instruction for handling errors is analoguous. The H register is a stack of handler–context
pairs:
H =
| hλX.M, Ei H
We call the new machine the CCH machine, where the “H” stands for “handler stack.” The
first six CC instructions, the ones for for plain ISWIM expressions, essentially remain the same;
they do not use the additional register in any way and do not alter it. (The handler-extended
CC machine uses Eh in place of E for the original CC rules, but the CCH machine continues
to use E in the rules, because the handler part of the context has been moved into the handler
stack, H.)
10.3 Machines for Exceptions 109
b if hM, [ ], i 7−→
→cch hb, [ ], i
evalcch (M ) = function if hM, [ ], i 7−→
→cch hλX.N, [ ], i
errb if hM, [ ], i 7−→
→cch h(throw b), [ ], i
For a correctness proof of the CCH machine, we must find a relationship between the states
of the extended CC machine and those of the CCH machine. The idea for the conversions is
the above-mentioned representation invariant: the standard context of a CC machine state is
represented as a stack of handlers and evaluation contexts. Conversely, given such a stack, we
can simply create a single standard context that creates the stack. Based on this idea, it is easy
to prove the equivalence between the two machines.
Exercise 10.15. Derive extended CK and CEK machines based on the CCH machine.
Exercise 10.16. Design a modified CCH machine that reserves a new register for the current
error handler. Prove its equivalence with the above CCH machine.
110 Chapter 10: Errors and Exceptions
111
int sum(int n) {
int i = 0;
while (n > 0) {
i = i + n;
n = n - 1;
}
return i;
}
In a purely functional style, we can implement the same loop using tail recursion and accumu-
lator arguments, as in the following Scheme function:
(define (sum n i)
(if (zero? n)
i
(sum (- n 1) (+ i n))))
In general, however, state is not so easily eliminated. Adding assignments or mutation operators
provides a whole new set of interesting programming paradigms, especially when added to
languages with higher-order procedures and complex data structures. In such a language,
programs can create, manipulate, and alter cyclic data structures and recursive nestings of
procedures. A program can also create a kind of “object”: a bundle consisting of data and
procedures for changing the data in the bundle, where other parts of the program can only
inspect or change the data through the procedures.
In this chapter, we extend ISWIM to accomodate state directly. The encoding of state for
loops, as above, suggests a way of handling state in a machine that manipulates text instead
of memory locations. Just as the state in n and i from the C program above is emulated by
passing arround n and i Scheme variables, we will model state in general as an entity that is
passed around in the evaluator.
The idea of state flows most naturally from a machine point of view, so we approach a model
of state in terms of a machine.
When a language provides assignment statements for identifiers, the nature of identifiers no
longer resembles that of mathematical variables. A mathematical variable represents some
fixed value, but assignable identifiers denote a varying association between names and values.
We call the association of an identifier with a current value as its state and refer to the execution
of assignments as state changes.
Evaluating the expression ((λx.((λy.x) (:= x (+ x d 1e )))) d 12e ) must therefore proceed
roughly like the following:
112 Chapter 11: Imperative Assignment
Note that a store address is not a value, which means that when a variable (replaced by a store
address) is used as an argument to a function, we must extract the value from the store before
applying the function. That’s the behavior we want for a call-by-value language, as opposed to
a call-by-reference language.
To define evaluation, we define the CS machine, which transforms expression-store pairs
hM, Σi:
.
(let X = M in N ) = ((λX.N ) M )
.
(begin M N ) = (let X = M in N )
where X 6∈ F V (N )
LS(σ) = {σ}
LS(b) = ∅
LS(X) = ∅
LS(void) = ∅
LS( (λX.M ) ) = LS(M )
LS( (M1 M2 ) ) = LS(M1 ) ∪ LS(M2 )
LS( (on M1 . . . Mn ) ) = LS(M1 ) ∪ . . . LS(Mn )
LS( (:= X M ) ) = LS(M )
Any σ that is in dom(Σ) but not in LS(hM, Σi) is a garbage slot. We can add a rule to 7−→cs
that removes a set of garbage slots:
Adding this rule to 7−→cs makes it non-deterministic in two ways. First, the rule can apply at
the same time as other rules, which means that the programmer does not know when a garbage
collection will occur. Second, the rule could match with different sets of σs, which means that
a programmer does not know which slots are freed when a collection does occur.
More importantly, if we ignore memory constraints, an evaluation of M with as many
garbage collection steps as possible will always produce the same result as an evalution of M
without any garbage collection steps. In other words, the garbage collector proves that certain
slots will never contribute to evaluation, so that it is safe to remove them from the store.
If we consider memory constraints, then we need to ensure that the garbage collection rule
is used often enough, and that it collects enough garbage. One possibility is to change the
machine so that a garbage collection occurs with every reduction, and that the resulting Σ is
the smallest possible one after each step; this strategy is similar to requiring that environments
are pruned on every closure creation (as in Section 8.3). As it turns out, a unique minimal Σ
exists for each step, so the resulting machine would be deterministic. However, performing a
garbage collection after every evaluation step is not a practical implementation. We return to
the question of a practical implementation in Section 11.4.
Exercise 11.2. Suppose that we add a simpler garbage-collection rule to 7−→cs that always
collects a single garbage slot:
hM, Σ[σ ← V ]i 7−→cs hM, Σi
if σ 6∈ LS(hM, Σi)
Why is this rule generally not sufficient to ensure proper garbage collection? (Hint: Why did
we ignore reference counting as a possible strategy for memory management?) Provide an
expression with the following properties:
116 Chapter 11: Imperative Assignment
2. It loops in bounded space when the [csgc] rule is used occasionally (i.e., never twice in
consecutive steps).
3. It cannot loop in bounded space using the simpler rule above (even if the rule is applied
multiple times in consecutive steps).
Hint: no plain ISWIM expression meets all three conditions. We introduce garbage collection
in this chapter because we did not need it before.
Most of the reduction rules for CEKS are the same as the CEK rules, except that they propagate
a store. Function application and variable look are changed, however. In the follow definition,
the rules with an asterisk are new or significantly revised compared to the CEK rules:
hh(M N ), Ei, κ, Σi 7−→ceks hhM, Ei, harg, hN, Ei, κi, Σi [ceks1]
hh(on M N . . .), Ei, κ, Σi 7−→ceks hhM, Ei, hopd, hon i, hhN, Ei, . . .i, κi, Σi [ceks2]
0 0
hhV, Ei, hfun, h(λX.M ), E i, κi, Σi 7−→ceks hhM, E [X ← σ]i, κ, Σ[σ ← hV, Ei]i [ceks3]∗
if V 6∈ X if σ 6∈ dom(Σ)
0 0
hhV, Ei, harg, hN, E i, κi, Σi 7−→ceks hhN, E i, hfun, hV, Ei, κi, Σi [ceks4]
if V 6∈ X
hhb, Ei, 7−→ceks hhV, ∅i, κ, Σi [ceks5]
hopd, hhbi , E i i . . . hb1 , E 1 i, on i,
hi, κi,
Σi
where δ(on , b1 , . . . , bi , b) = V
0
hhV, Ei, 7−→ceks hhN, E i, [ceks6]
hopd, hc0 , . . . on i, hopd, hhV, Ei, c0 , . . . on i, hc, . . .i, κi,
0
hhN, E i, c, . . .i, κi, Σi
Σi
if V 6∈ X
hhX, Ei, κ, Σi 7−→ceks hc, κ, Σi [ceks7]∗
where Σ(E(X)) = c
hh(:= X M ), Ei, κ, Σi 7−→ceks hhM, Ei, hset, hX, Ei, κi, Σi [ceks8]∗
0 0
hhV, E i, hset, hX, Ei, κi, Σi 7−→ceks hhvoid, ∅i, κ, Σ[σ ← hV, E i]i [ceks9]∗
if V 6∈ X where E(X) = σ
11.4 Implementing Garbage Collection 117
b if hhM, ∅i, mt, ∅i 7−→
→ceks hhb, Ei, mt, Σi
evalceks (M ) = →ceks hhλX.N, Ei, mt, Σi
function if hhM, ∅i, mt, ∅i 7−→
if hhM, ∅i, mt, ∅i 7−→
→ceks hhvoid, Ei, mt, Σi
void
Note that none of the rules for the CEKS machine insert store addresses into an expression
position; they are all in the domain of Σ and the range of E. Thus, if we want to add a
garbage-collection rule to our CEKS machine, we need to define the set of live slots based on
the machine’s current environment. In addition, the continuation may contain environments,
so the live slot calculation needs to check the machine’s continuation, and value closures in Σ
also contain environments.
hhM, Ei, κ, Σ[σ1 ← hV1 , E 1 i] . . . [σn ← hVn , E n i]i 7−→cs hhM, Ei, κ, Σi [ceksgc]
if σ1 , . . . σn 6∈ LS(E) ∪ LS(κ) ∪ LS(Σ)
LS(E) = rng(E)
LS(mt) = ∅
LS(hfun, hV, Ei, κi) = LS(E) ∪ LS(κ)
LS(harg, hN, Ei, κi) = LS(E) ∪ LS(κ)
LS(hopd, hhVi , E i i, . . . om i, hhMj , E j i, . . .i, κi) = LS(E i ) ∪ . . . LS(E j ) ∪ . . . LS(κ)
LS(hset, hX, Ei, κi) = LS(E) ∪ LS(κ)
hhM, Ei, κ, Σi 7−→cs hhM, Ei, κ, ∅[σ1 ← Σ(σ1 )] . . . [σn ← Σ(σn )]i [ceksgc]
if hLS(M ) ∪ LS(E), ∅, Σi 7−→
→gc h∅, {σ1 , . . . σn }, Σi
This rule determines a unique and minimal store for a garbage collection step in the CEK
machine. At this point, the only missing part of the specification is a way to ensure that the
[ceksgc] rule is used frequently enough.
Exercise 11.3. Implement the CEKS machine. Every other step taken by your CEKS machine
should be a [ceksgc] step that collects as many slots as possible.
11.5 History
The apporach to specifying garbage collection with 7−→gc is due to Morrisett, Felleisen, and
Harper [6].
Part III
119
121
A type relation (or type system) implements the last of the above possibilities. A language
that consists of an expression grammar, evaluation relation, and type relation is a typed
language. Each language that we have studied so far, which comprised only an expression
grammar and a reduction relation, was an untyped language.
The design of a type system is an open-ended task: since any type system for a realistic
language must reject some set of programs that do not get stuck, we can always search for
an improved type system that rejects fewer good programs. In this chapter, we begin our
exploration of types with a small language and a simple type checker. In the following chapters,
we explore a series of type systems for ISWIM.
N = t
| f
| d e
n
| (+ N N )
| (iszero N )
| (if N N N )
(+ d ne d me ) z d
n + me
(iszero d 0e ) z t
(iszero d ne ) z f where n 6= 0
(if t N1 N2 ) z N1
(if f N1 N2 ) z N2
C = [] E = [] V = t
| (+ C N ) | (+ E N ) | f
| (+ N C) | (+ V E) | d ne
| (iszero C) | (iszero E)
| (if C N N ) | (if E N N )
| (if N C N )
| (if N N C)
(if (+ d 1e d 5e ) t d 0e )
gets stuck because the test expression for if does not produce a boolean.
Since the language for N is not Turing-complete, we could actually define an type checker
based on evaluation. In preparation for more interesting languages, however, we will adopt a
less precise strategy that scales to more interesting languages.
The key idea is that programs get stuck because the wrong kind of value flows into a position
where the reduction rules inspect the value. The + operator expects numbers, iszero expects
numbers, and if expects booleans.
We will therefore design a relation that associates expressons with types. Like an expression,
a type in the formal sense is a purely syntactic entity. In the same way that we define formal
evaluation relations based on an intution of how expressions should be evaluated, we also define
12.1 Numbers and Booleans 123
a formal type relation based on our intutions about the kinds of values that appear during
evaluation.
For our number and boolean language, we first define the set of types T :
T = bool
| num
The relation ` : matches expressions with types. Literal boolean expressions have the type
bool, and literal numbers have the type num:
` t : bool
` f : bool
` d ne : num
We might also introduce a rule that assigns every addition expression the type num. However,
we will use ` : both to describe the kind of value returned by an expression, and to identify
expressions that cannot get stuck. In other words, we want to design ` : so that if ` N : T
for some N and T , then N cannot get stuck.
Thus, we want an addition expression to have type num only if its subexpressions also have
type num. The iszero rule is similar, except that it gets the type bool:
` N1 : num ` N2 : num
` (+ N1 N2 ) : num
` N : num
` (iszero N ) : bool
The only remaining expression form is if. Clearly, the first sub-expression of an if expression
should have type bool, but the z rule for if makes no requirements on the other expressions.
This analysis suggests a rule of the shape:
` N1 : bool
` (if N1 N2 N3 ) :
But what is the type for the entire if expression? If N1 evaluates to t, the result of the if
expression is the result of N2 . If N1 instead evaluates to f, the result of the if expression is
the result of N3 . Since we do not want to evaluate N1 to type-check the expression, we are
forced to require that N2 and N3 both have the same type, and that type is the one for the if
expression:
` N1 : bool ` N2 : T ` N3 : T
` (if N1 N2 N3 ) : T
This rule can match with T as bool or as num, but all three instances of T must match the
same type.
At this point, we have a complete set of type rules for N and v. We can see that
(if (if t f t) d 0e d 1e ) is categorized as a “good” expression, since ` : assigns it a type:
` t : bool ` f : bool ` t : bool
` (if t f t) : bool ` d 0e : num ` d 1e : num
` (if (if t f t) 0 1 ) : num
d e d e
In contrast, (if d 7e d 0e d 1e ) has no type, since 6` d 7e : bool. The following example also has no
type:
(if t d 1e f)
124 Chapter 12: Types
despite the fact that it reduces via 7−→z to d 1e . Our type system is thus conservative in the
expressions it designates as “good”. Whether this conservatism is acceptable depends on a
programmer’s needs, just like any other aspect of the language.
Lemma 12.1 [Unique Evaluation Context for 7−→z ]: If N 6∈ V , then there
exist E and N 0 such that N = E[N 0 ] and N has one of the following forms:
• (+ V1 V2 )
• (iszero V )
• (if V N1 N2 )
Exercise 12.1. Prove that ` (if (iszero d 3e ) (iszero (+ d 1e d 3e )) t) : bool (i.e., show the
proof tree).
12.2 Soundness
A typed language is sound if its type system and evaluation rules are consistent, i.e., if the type
system assigns an expression a type, then the expression does not get stuck when evaluated.
Theorem 12.5 [Soundness of ` : and 7−→
→z ]: If ` N : T , then either
• N 7−→
→z V , or
→z N 0 implies that N 0 7−→z N 00 for some N 00 .
• N 7−→
To prove the soundness theorem, we develop a pair of lemmas. The first is a preservation
(or subject reduction) lemma that says when 7−→z maps a typed expression to some other
expression, the expressions have the same type. The second is a progress lemma, which says
that 7−→z relates every non-V typed expression to some other expression. Together, these
lemmas prove the soundness theorem. This technique for proving soundness was developed by
Wright and Felleisen.
Lemma 12.6 [Preservation for 7−→z ]: If N 7−→z N 0 and ` N : T , then ` N 0 : T .
Proof for Lemma 12.6: Since, N 7−→z N 0 , there must be some E, N1 , and
N10 such that N = E[N1 ] where N1 z N10 . By Lemma 12.3 there must be some T1
such that ` N1 : T1 . Consider all cases for N1 z N10 , which will prove a sub-claim,
` N10 : T1 :
• Case (+ d ne d me ) z d n + me
Since ` d ne : num and ` d me : num, ` (+ d ne d me ) : num so T1 = num. Similarly,
` d n + me : num, so the sub-claim holds.
12.2 Soundness 125
• Case (iszero d 0e ) z t
Since ` d 0e : num, T1 = bool. Since ` t : bool, the sub-claim holds.
• Case (iszero d ne ) z f
Analogous to the previous case.
• Case (if t N2 N3 ) z N2
By assumption, ` (if t N2 N3 ) : T1 , so whatever T1 is, it must be possible to
show ` N2 : T1 . Thus, the sub-claim holds.
• Case (if f N2 N3 ) z N3
Analogous to the previous case.
Finally, by Lemma 12.4, ` E[N10 ] : T , so the original claim holds.
Lemma 12.7 [Progress for 7−→z ]: If ` N : T , then either N ∈ V or N 7−→z N 0
for some N 0 .
Proof for Lemma 12.7: By induction on the structure of N .
• Base cases:
– Case N = t
t∈V.
– Case N = f
t∈V.
– Case N = d ne
n ∈V.
d e
• Inductive cases:
– Case N = (+ N1 N2 )
There are three sub-cases:
∗ Case N1 6∈ V
By Lemma 12.1, N1 = E[N0 ] for some E and N0 6∈ V . By assumption,
` (+ N1 N2 ) : T , which requires ` N0 : T0 for some T0 . By induction,
N0 7−→z N00 ; in particular, N0 z N00 due to the partitioning of N1 into E
and N0 . Let E 0 = (+ E N2 ); then N = E 0 [N0 ] and E 0 [N0 ] 7−→z E 0 [N00 ].
∗ Case N2 6∈ V
Analogous to the previous case.
∗ Case N1 = V1 , N2 = V2
Since ` (+ N1 N2 ) : T , ` N1 : num and ` N2 : num. By inspection
of V , we see that the only members of V that have type num are
numbers: d ne . Thus, N = (+ d ne1 d ne2 ). By the definition of 7−→z ,
N 7−→z d n1 + n2 e .
– Case N = (iszero N1 )
Analogous to the previous case.
– Case N = (if N1 N2 N3 )
There are two sub-cases:
∗ Case N1 6∈ V
This case is analogous to the first sub-case of N = (+ N1 N2 ).
∗ Case N1 = V1
Since ` (if N1 N2 N3 ) : T , ` N1 : bool. By inspection of V , we
see that the only members of V that have type bool are t and f. If
N1 = t, then N 7−→z N2 , and if N1 = f then N 7−→z N3 .
Exercise 12.6. Prove Theorem 12.5 (Soundness). Begin by proving a multi-step presevation
→z N 0 and ` N : T , then ` N 0 : T .
lemma: If N 7−→
126 Chapter 12: Types
127
We are now ready to consider a typed variant of ISWIM that can reject expressions such as
(+ d 1e (λx.d 9e ))
Our simple language from the previous chapter had exactly two types: bool and num. Since
ISWIM is parameterized over the basic constrants and primitive operations, a typed ISWIM
will also be parameterized over the basic types. But, as the expression above illustrates, a typed
ISWIM will always need at least one type: the type for functions.
In this chapter, we present Simply Typed ISWIM, which illustrates a simple type system
for functions.
T = num
| function
T = B
| (T → T )
B = a basic type
The set B depends on the basic constants b. For our running example b, we define B to contain
only a token for number types:
B = num
128 Chapter 13: Simply Typed ISWIM
Before defining type rules, we must address one more aspect of Simply Typed ISWIM expres-
sions. Consider the function
λx.x
Its type might be (num → num) if we want to use it on numbers, but the function works just as
well on any kind of value, including other functions. Without more information about the kind
of value that x is supposed to be, the type rules will have to guess. To avoid this problem (for
now), we modify the expression grammar of Simply Typed ISWIM so that the formal argument
of a function is annotated with an explicit type, indicating the kind of value that the function
expects to consume. Thus, the above expression must be written as
λx:num.x
λx:(num → num).x
M = X
| (λX:T.M )
| (M M )
| b
| (on M . . . M )
` M1 : B 1 . . . ` Mn : B n
n
` (o M1 . . . Mn ) : T where ∆(on ) = hhB1 , . . . Bn i, T i
For our basic constants and primitive operations, B maps all basic constants to num, and ∆
requires num arguments for all operations.
B(b) = num
Now that we have rules for basic constants and primitive operations, we need rules for expres-
sions of the form X, (λX.M ), and (M M ).
What type should a variable X have? For evaluation, we never needed to consider the
value of a variable, because the reduction rules caused (bound) variables to be replaced with
13.2 Type Rules for Simply Typed ISWIM 129
values before the variable itself was evaluated. In the CEK machine, we saw that environments
provided an equivalent notion of evaluation without rewriting the body of a function.
For the type checker, we will use an environment to handle variables. This choice emphasizes
that type checking is static (i.e., the type checker only inspects an expression, and does not
evaluate it). For type checking, instead of mapping variables to values, a environment Γ maps
variables to types. We implement the enviornment as a sequence of type associations:
Γ =
| Γ, X:T
Γ(X) = T if Γ = Γ0 , X:T
Γ(X) = Γ (X) if Γ = Γ0 , X 0 :T and X 6= X 0
0
The type relation for Simply Typed ISWIM maps pairs Γ and M to a type T , written as
Γ ` M : T . For many rules, like the ones for basic constants and primitive operations, the
environment is simply passed along to type subexpressions, but the environment is consulted
to assign a type to a variable.
Γ`X:T if Γ(X) = T
Γ`b:B if B(b) = B
Γ ` M1 : B 1 . . . Γ ` Mn : B n
Γ ` (on M1 . . . Mn ) : T where ∆(on ) = hhB1 , . . . Bn i, T i
The type environment must be extended to assign a type to the body of a λ expression. For
example, the expression
λx:num.(+ x d 3e )
is a function, so it should have a type of the form (T → T ). The type for the left-hand side
of the arrow is provided by the programmer: num. To get the type for the right-hand side, we
must check the body expression (+ x d 3e ) in an environment where x is mapped to num.
More generally, the rule for checking a function expression is as follows:
Γ, X:T ` M : T 0
Γ ` (λx:T.M ) : (T → T 0 )
Finally, the type of an application expression (M N ) depends on the kind of value that the
function M returns. In particular, since M must produce a function, it must have an arrow
type, and the right-hand side of the arrow type determines the result type of the application.
Furthermore, the type of N must match the type of argument value expected by M , which is
the left-hand side of the arrow type.
Γ ` M : (T 0 → T ) Γ ` N : T 0
Γ ` (M N ) : T
The following example illustrates typing with functions, using n as an abbreviation for num:
Note that “Γ” never appears in the above proof tree, in the same way that “M ” and “T ” never
appear. Instead, just as “M ” in the rules is replaced by a specific expression, “Γ” is replaced
by a specific type environment.
13.3 Soundness
We can prove that our type rules for Simply Typed ISWIM are sound with respect to 7−→v as
long as δ is consistent with B and ∆. In other words, we require the following assumption for
any δ, B, and ∆.
With this assumption, we can prove the soundness of Simply Typed ISWIM using the same
technique as in the previous section: we define and prove Preservation and Progress lemmas.
Theorem 13.1 [Soundness of Simply Typed ISWIM]: If ` M : T , then either
• M 7−→→v V , or
• M− →v M 0 implies that M 0 7−→v M 00 for some M 00 .
7 →
Lemma 13.2 [Preservation for Simply Typed ISWIM]: If M 7−→v N and
` M : T , then ` N : T .
Lemma 13.3 [Progress for Simply Typed ISWIM]: If ` M : T , then either
M ∈ V or M 7−→v N for some N .
As before, the above lemmas rely on a set of minor lemmas about unique types and types in
context:
Lemma 13.4: If ` M : T and ` M : T 0 , then T = T 0 .
Lemma 13.5: A proof tree for ` C[M ] : T contains a proof tree for Γ ` M : T 0 for
some Γ and T 0 .
Lemma 13.6: If a proof tree for ` C[M ] : T contains a proof tree for Γ ` M : T 0 ,
then Γ ` N : T 0 implies ` C[N ] : T .
In addition, because the type rules work with type environments while the evalution rules
use substitution, we need a lemma that relates the types of an expression before and after
substitution:
Lemma 13.7: If Γ, X:T 0 ` M : T and ` V : T 0 , then Γ ` M [X ← V ] : T .
Exercise 13.2. Prove Lemma 13.2 (Preservation), assuming the other lemmas above.
Exercise 13.3. Prove Lemma 13.3 (Progress), assuming the other lemmas above.
13.4 Normalization 131
13.4 Normalization
In the number and boolean language of the previous chapter, the evaluation of any typed
expression terminates. This fact is fairly obvious, since every expression in the language either
gets stuck or terminates; there is no way to write a loop.
We have seen many looping ISWIM expressions, such as Ω. We might ask, then, whether any
Simply Typed ISWIM expression that has a type can loop. The answer, perhaps surprisingly, is
“no” (assuming well-behaved primitive operations, as explaiend below). Every typed expression
in Simply Typed ISWIM terminates!
A corollary of the above claim is that Ω has no well-typed representation in Simply Typed
ISWIM. To see why, recall that Ω is
(λx.x x) (λx.x x)
To make Ω a Simply Typed ISWIM expression, we need an explicit type T for the argument x:
(λx:T.x x) (λx:T 0 .x x)
If there is such a T , then it must be an arrow type (T1 → T2 ), since the argument x is applied
as a function. Furthermore, since x is applied to itself, the left-hand side of the arrow type, T1 ,
must be the same as the type for x, i.e., T1 = (T1 → T2 ). But now we have a problem, one
that is reminiscent of our attempt to define the recursive function mult as an abbreviation: we
cannot expand T1 to a type expression that does not contain T1 .
In short, we have no way to write a type for x. The Y-combinator trick that we used for
mult not work for T1 , because we have nothing equivalent to λ in the type language (i.e., we
cannot abstract over type expressions).
We have allowed primitive operators to generate arbitrary values, including λ expressions,
so a primitive operator might circumvent Ω’s problem by generating a closed expression that
contains the original operator. We could ensure that primitive operators do not “misbehave”
in this way by introducing one more assumption about the primitives:
Assumption 2:
δ(on , b1 , . . . bn ) = (λX.M ) implies M contains no primitive operations
Even ignoring the complications of this assumption, simple induction does not suffice to prove
that all typed expressions terminate. Roughly, the problem is that a βv reduction generates an
expression that is not a sub-structure of the original expression (due to variable substitutions),
so the obvious inductive hypothesis does not apply.
Instead, the proof requires an auxilliary relation, V:
V(M, B) if `M :B
and M 7−→
→v V for some V
V(M, (T1 → T2 )) if ` M : (T1 → T2 )
and M 7−→
→v V for some V
and V(N, T1 ) implies V( (M N ), T2 )
The V( , ) relation captures the notion that an expression terminates, and that it can be put
into any context and not affect the termination of the context. We can easily prove that a
single evaluation step preserves this “deep termination” property of an expression:
• Base case:
– Case T = B
If either M or N terminates, then clearly both terminate with the same V .
Furthermore, M and N have the same type by Presevation, so the claim
holds.
• Inductive case:
– Case T = (T1 → T2 ) for some T1 and T2
Assume that V(M, T ), so that M 7−→ →v V for some V , and V(N 0 , T1 ) for
0 0
any N implies V( (M N ), T2 ). Clearly N 7−→ →v V . Since M 7−→v N , we
have (M N 0 ) 7−→v (N N 0 ). Thus, by induction, V( (N N 0 ), T2 ).
If we assume V(N, T ), we can similarly conclude V(M, T ).
We are now ready to prove the main lemma. The primitive-operation rule can break the
induction we’d like to use, so at first we leave it out. We then prove a similar lemma that
supports primitive operations, as long as they satisfy Assumptions 1 and 2.
Lemma 13.9: If Γ = X1 :T1 , . . . Xn :Tn and the following hold:
• M contains no primitive applications,
• Γ ` M : T , and
• V(V1 , T1 ), . . . V(Vn , Tn ) for some V1 , . . ., Vn ,
then V(M [X1 ← V1 ] . . . [Xn ← Vn ], T ).
• Base cases:
– Case Γ ` X : T
X must be some Xi for i ∈ [1, n]. Thus, X[X1 ← V1 ] . . . [Xn ← Vn ] = Vi ,
and we have assumed V(Vi , T ), so the claim holds.
– Case Γ ` b : T
T ∈ B, b[X1 ← V1 ] . . . [Xn ← Vn ] = b, and b ∈ V clearly terminates, so
the claim holds.
• Inductive cases:
– Case Γ ` (λX:T1 .N ) : T
T must be of the form (T1 → T2 ), where Γ, X:T1 ` N : T2 . Clearly
M 0 = M [X1 ← V1 ] . . . [Xn ← Vn ] terminates, since M is a value. Choose
an arbitrary N 0 such that V(N 0 , T1 ). To prove the claim, we must show
that V( (M 0 N 0 ), T2 ).
By the definition of V, N 0 7−→ →v V for some V ; since M 0 is a value, we can
0 0 0
see that (M N ) 7−→ →v (M V ). By βv , this expression reduces further to
– Case Γ ` (M1 M2 ) : T
By the type rule for application and by induction,
and
V(M2 [X1 ← V1 ] . . . [Xn ← Vn ], T1 )
for some T1 . Since M1 has an arrow type, by the definition of V,
• Γ ` M : T , and
• V(V1 , T1 ), . . . V(Vn , Tn ) for some V1 , . . ., Vn ,
then V(M [X1 ← V1 ] . . . [Xn ← Vn ], T ).
Proof for Lemma 13.10: The proof is analogous to the proof for Lemma 13.9,
except that the primitive operation case must be addressed.
• Case Γ ` (om M1 . . . Mm ) : T
as desired.
134 Chapter 13: Simply Typed ISWIM
135
Since all Simply Typed ISWIM programs terminate, clearly we have lost some expressive power
in the typed version of ISWIM. In particular, we can no longer write recursive programs. As we’ll
see in the following sub-sections, we have also lost the ability to encode complex conditionals,
or to encode data structures such as pairs.
To recover useful kinds of expressiveness in a typed setting, we can refine the core type rules
so that they allow more programs, including the ones that implement conditionals and pairs.
We explore that approach in future chapters.
Meanwhile, in this chapter, we explore a simpler approach: extend Simply Typed ISWIM
with explicit constructs for conditionals, pairs, etc. With these constructs in the language,
we can define type rules that work directly on the constructs. In other words, the explicit
constructs provide a place to hang specific type rules that directly reflect our intuition about
the constructs.
14.1 Conditionals
In Chapter 12, we defined a language of booleans and numbers with a built-in if form for
conditionals. In contrast, for plain ISWIM, we used the encoding or true and false that we first
developed for the pure λ-calculus of Chapter 4, where true is (λx.λy.x) and false is (λx.λy.y).
The iszero primitive operation cooperates with this encoding, mapping a number to either
(λx.λy.x) or (λx.λy.y), and the if0 macro combines the function encoding of true and false
with applications to achieve a conditional branch.
For Simply Typed ISWIM, we have to pick typed functions to use for encodings of true
and false. Indeed, when assigning a ∆ mapping for iszero, we implicitly picked a typed
encoding; the result type for iszero was defined as (num → (num → num)), which is the type of
(λx:num.λy:num.x) and (λx:num.λy:num.y). Thus, we can write
((iszero d 0e ) d 1e d 2e )
which evaluates to d 1e , and is also well-typed. But, unfortunately, we cannot redefine the if0
macro to work with this encoding:
.
(if0 K M N ) = (((iszero K) (λX:num.M ) (λX:num.N )) d 0e )
where X 6∈ FV(M ) ∪ FV(N )
The problem is that the first argument to the result of (iszero K) will have a type (num → ),
while the typed encoding of true and false expects an argument of type num. To solve this
problem, we might choose a different encoding for booleans:
.
true = (λx:(num → num).λy:(num → num).x)
.
false = (λx:(num → num).λy:(num → num).y)
··· ···
` ((iszero d 0e ) (λx:n.d 1e )) : ((n → n) → (n → n)) ` ((λx:n.d 2e )) : (n → n)
` ((iszero d 0e ) (λx:n.d 1e ) (λx:n.d 2e )) : (n → n) ` d 0e : n
` (((iszero d 0e ) (λx:n.d 1e ) (λx:n.d 2e )) d 0e ) : n
136 Chapter 14: Variations on Simply Typed ISWIM
Neverthless, the new encoding is still limited. Conditionals using iszero can only be well-
typed when they produce numbers. We have lost the ability to write conditionals that produce
functions, as in
(if0 d 0e (λx:num.(add1 x)) (λx:num.(sub1 x)))
The easiest way to support such expressions is to add booleans and a conditional form directly
into Simply Typed ISWIM.
M = ...
| f
| t
| (if M M M )
T = ...
| bool
Γ ` M1 : bool Γ ` M2 : T Γ ` M3 : T
Γ ` (if M1 M2 M3 ) : T
Exercise 14.1. Complete the extension of Simply Typed ISWIM for booleans and if, including
new type rules for t and f, extended definitions for contexts and evaluation contexts, and new
evaluation rules to go with βv and δ. Then show that
14.2 Pairs
Recall the encoding of pairs from Chapter 4:
.
mkpair = λx.λy.λs.(s x y)
.
fst = λp.(p λx.λy.x)
.
snd = λp.(p λx.λy.y)
The problem with these encodings in a typed setting is similar to the problem with true and false:
we have to pick a specific type for x and y in mkpair. Unlike the problem with conditionals,
however, no primitive operations are involved that require a fixed type for pairs. We might
therefore try to define a family of abbreviations, one for each pair of types T1 and T2 , where
T1 is the type of the first element in the pair, and T2 is the type for the second element.
.
mkpair(T1 ×T2 ) = λx:T1 .λy:T2 .λs:(T1 → (T2 → )).(s x y)
.
fst(T1 ×T2 ) = λp:((T1 → (T2 → T1 )) → T1 ).(p λx:T1 .λy:T2 .x)
.
snd(T1 ×T2 ) = λp:((T1 → (T2 → T2 )) → T2 ).(p λx:T1 .λy:T2 .y)
This encoding nearly works. The problem is that fst(T1 ×T2 ) and snd(T1 ×T2 ) must return different
kinds of values if T1 6= T2 , but the two functions flow into the same s in mkpair(T1 ×T2 ) . Thus,
there is no good type to put in place of in the definition of mkpair(T1 ×T2 ) , unless we restrict
T1 and T2 to be the same.
14.3 Variants 137
We can solve the problem more generally by adding pairs and pair types directly to Simply
Typed ISWIM. The form hM, N i pairs the values of M and N together, and the fst and snd
forms extract a value from a pair. The type for a pair is (T1 × T2 ).
(fst hV1 , V2 i) p V1
v = ... ∪ p
(snd hV1 , V2 i) p V2
Γ ` M1 : T 1 Γ ` M2 : T 2
Γ ` hM1 , M2 i : (T1 × T2 )
Γ ` M : (T1 × T2 ) Γ ` M : (T1 × T2 )
Γ ` (fst M ) : T1 Γ ` (snd M ) : T2
Exercise 14.2. Using both the conditional and pair extensions, show that (fst h(add1 d 0e ), ti)
has a type and a value.
14.3 Variants
Some functions need to accept multiple kinds of values that implement variants of an abstract
datatype. For example, a list-processing function must accept both a constant representing the
empty list, null, and a cons cell (cons v l), where v is the first element in the list and l is the
rest of the list. In addition to accepting both kinds of values, the function must somehow be
able to distinguish them.
We can implement such variants in untyped ISWIM by using pairs and attaching a different
tag to each variant. The true tag can identify the empty list, and the false tag can identify a
cons cell: .
null = htrue, falsei
.
cons = λv.λl.hfalse, hv, lii
.
isnull = λl.fst l
In a typed language, the above encoding does not work. The null constant has the type (bool ×
bool), whereas a cons cell has type (bool × (T × T 0 )) for some T and T 0 . These types are
incompatible, so we cannot write an isnull function that accepts arguments of both shapes.
Once again, we solve the problem by extending our core language. We will extend it with a
notion of variants (or disjoint sums), represented by the type (T1 + T2 ) for variant types T1
and T2 . A value of type (T1 + T2 ) encapsulates either a value of type T1 or a value of type T2 .
Three new forms operate on variants of type (T1 + T2 ): ToLeft(T1 +T2 ) , ToRight(T1 +T2 ) , and
Match((T1 +T2 )→T ) .
• (ToLeft(T1 +T2 ) M )
This form computes the value for M , which must be of type T , and encapsulates it as
value of type (T1 + T2 ). In other words, ToLeft(T1 +T2 ) injects a value of type T into
(T1 + T2 ).
• (ToRight(T1 +T2 ) M )
This form injects the value of M , of type T2 , into (T1 + T2 ).
138 Chapter 14: Variations on Simply Typed ISWIM
With the new forms, we can take a step towards encoding lists. Lists of arbitrary length require
even more typing machinery than we have developed so far, but we can at least define a datatype
that encapsulates either an empty list or a “list” containing a single number:
.
null = (ToLeft(bool+num) f)
.
list1 = λv:num.(ToRight(bool+num) v)
.
isnull = λl:(bool + num). (Match((bool+num)→bool) l
(λx:bool.t)
(λx:num.f))
M = ... E = ...
| (ToLeft(T +T ) M ) | (ToLeft(T +T ) E)
| (ToRight(T +T ) M ) | (ToRight(T +T ) E)
| (Match((T +T )→T ) M M M ) | (Match((T +T )→T ) E M M )
| (Match((T +T )→T ) V E M )
V = ... | (Match((T +T )→T ) V V E)
| (ToLeft(T +T ) V )
| (ToRight(T +T ) V ) T = ...
| (T + T )
Γ ` M : T2
Γ ` (ToRight(T1 +T2 ) M ) : (T1 + T2 )
Exercise 14.3. using the macro definitions above, show that (isnull (list1 d 13e )) has a type and
a value.
14.4 Recursion
Using the conditional extension from Section 14.1, we can define a typed version of the mksum
function:
.
mksum = λf :(num → num).λn:num.(if (iszero n) d 0e (+ n (f (sub1 n))))
But we know that Simply Typed ISWIM doesn’t allow recursion, so we should expect that
Yv mksum
14.4 Recursion 139
Γ ` M : ((T1 → T2 ) → (T1 → T2 ))
Γ ` (fix M ) : (T1 → T2 )
Since T1 and T2 only appear within (T1 → T2 ), we can simplify the rule by using T in place of
(T1 → T2 ). The complete extension of the language is as follows:
M = ... E = ...
| (fix M ) | (fix E)
v = ... ∪ y
Γ ` M : (T → T )
Γ ` (fix M ) : T
The y reduction rule implements the essense of the fixed-point equiation directly, so fix cer-
tainly acts like Yv . And, using the new type rule we have
···
` mksum : ((num → num) → (num → num))
` (fix mksum) : (num → num)
Thus, (fix mksum) is the recursive multiplication function for a type language.
The soundness theorem for Simply Typed ISWIM holds for the langauge extended with fix.
This is easy to see; if (fix (λX:T.M )) has type T , then X can be replaced by (fix (λX:T.M ))
in M without changing the type of M .
The normalization theorem no longer holds, as demonstrated by the following infinite loop:
Exercise 14.4. Prove that ` (fix (λx:T.x)) : T for any T . How is it possible that (fix (λx:T.x))
manufactures a value of type T out of thin air? For example, what number does (fix (λx:num.x))
produce when it is evaluated?
140 Chapter 14: Variations on Simply Typed ISWIM
141
With the extensions of the previous chapter, we can write many interesting programs in Simply
Typed ISWIM. We cannot necessarily write them as conveniently, however. For example,
instead of writing a single identity function
λx.x
we have to write for one every kind of value that we want to use as an argument to the identity
function
λx:num.x
λx:bool.x
λx:(num → num).x
λx:((bool → num) + (num × bool)).x
This duplication of code is wasteful—especially when the function is more complex than identity.
In this chapter, we extend our language and type rules so that we can once again write
functions, such as identity, that are polymorphic: they work simultaneously on many kinds
(or “shapes”) of data.1
A function that does not inspect its argument in any way is clearly a candidate for poly-
morphism, but some functions inspect their arguments only partially. For example, a swap
function
λp.hsnd p, fst pi
works only on pair obejcts, but it does not inspect the values in the pair. Thus, this function
is polymorphic, because it works on many different kinds of pairs.
The kind of abstraction that we need over many types is similar to the kind of abstraction
that λ provides over many specific values. This observation suggests that we extend Simply
Typed ISWIM with a mechanism for abstracting an expression over a type, and combining a
type-abstracted function with a specific type to get a specific function. The resulting language
is Polymorphic ISWIM. (Note: In the same way that the functional core of ISWIM is called
the λ-calculus, the functional core of Polymorphic ISWIM is sometimes called System F.)
where α is a placeholder for an unknown type (in the same way that x is a placeholder for an
unknown value).
Along with application for normal functions to values, we need type application for poly-
mophic functions to types. We distinguish type applications from normal applications by using
infix square brackets around a type argument. Thus, to apply id to the number d 5e , we write
(id[num] d 5e )
1 The kinf of polymorhpism that we explore in this chapter is sometimes called parameteric polymorphism.
The num type argument gets substituted for α in (λx:α.x) to produce a normal function, which
can then be applied to d 5e in the usual way.
A polymorphic swap function needs two types: one for the first element in the original pair,
and one for the second element of the original pair:
.
swap = Λα.Λβ.λp:(α × β).hsnd p, fst pi
swap[num][bool]
` id : (∀α.(α → α))
The swap example shows that type expressions, such as (α × β), can include type variables,
such as α and β. Thus, our new expression and type grammars are as follows:
M = ...
| (ΛA.M )
| M [T ]
V = ...
| (ΛA.M )
T = ...
| A
| (∀A.T )
A = a type variable: α, β, . . .
(ΛA.M )[T ] βt M [A ← T ]
v = . . . ∪ βt
where substitution for type variables is defined in the obvious way, and FV(T ) extracts the free
type variables of T in the obvious way.
To assign a type to Polymorphic ISWIM experssions, we need to track type variables in
an envionment along with normal variables. Up to now, Γ has mapped normal variables to
types. For Polymorphic ISWIM, we extend Γ so that it also contains type variables. The type
variables have no bindings (the implicit binding would be “is a type”), but they are needed in
the environment to disallow free type variables. For example, the expression
λx:α.x
should not have a type, because α has no meaning, in the same way that the expression
x
15.1 Polymorphic ISWIM 143
Γ =
| Γ, X:T
| Γ, A
Γ(X) = T if Γ = Γ0 , X:T
Γ(X) = Γ (X) if Γ = Γ0 , X 0 :T and X 6= X 0
0
Γ(X) = Γ0 (X) if Γ = Γ0 , A
Γ(A) if Γ = Γ0 , A
0
Γ(A) when Γ (A) if Γ = Γ0 , A0 and A 6= A0
Γ(A) when Γ0 (A) if Γ = Γ0 , X 0 :T
The type rules for type abstraction and type application use the environment with type vari-
ables. Furthermore, in expressions with type expressions (including λ expressions), the type
expression must be checked to ensure that it has no free type variables; the ` relation
performs this check.
Γ, A ` M : T Γ ` M : (∀A.T 0 ) Γ ` T
Γ ` (ΛA.M ) : (∀A.T ) Γ ` M [T ] : T 0 [A ← T ]
Γ, X:T ` M : T 0 Γ ` T
Γ ` (λX:T.M ) : (T → T 0 )
Γ ` A if Γ(A) Γ`B
Γ ` T1 Γ ` T2 Γ, A ` T
Γ ` (T1 → T2 ) . . . pair types, etc. . . . Γ ` (∀A.T )
Type abstractions introduce yet one more wrinkle into the type-checking process. The type rule
for function application sets up an implicit equation between the type of the argument expres-
sion, and the argument type of the function expression. But now that we have Λ abstractions
that parameterize over an arbitrary type variable, our type grammar includes expressions that
should be treated the same, but are not syntactically equivalent. For example, (Λα.(α → α))
and (Λβ.(β → β)) should be equivalent.
To allow such types to be treated the same, we must modify the application rule to use an
explicit equality check, and we must also define a set of rules ` ↔ for type equivalence.
Γ ` M : (T 0 → T ) Γ ` N : T 00 ` T 0 ↔ T 00
Γ ` (M N ) : T
` T1 ↔ T10 ` T2 ↔ T20
`T ↔T ` (T1 → T2 ) ↔ (T10 → T20 ) ...
Exercise 15.2. Although languages with polymorhpism typically also have a built-in notion of
pair, Polymorphic ISWIM supports the pure λ-calculus encoding of pairs, after the encoding is
augmented with appropriate types, Λ abstractions, and type applications. Show this encoding
(i.e., show versions of mkpair, fst, and snd that are well-typed in Polymorphic ISWIM).
144 Chapter 15: Polymorphism
145
Now that we have polymorphism in our language, we can write interesting programs without
duplicating functionality to satisfy the type system. Nevertheless, the type system still demands
a certain amount of work from the programmer that was not required in plain ISWIM. For
example, a programmer must write Λ and α in
Λα.λx:α.x
instead of simply
λx.x
to define the polymorphic identity function.
In this chapter, we study type inference (or type reconstruction), which relives the
programmer of writing type annotations, but does not sacrifice the benefits of a typed language.
The Type-Inferred ISWIM language allows a programmer to write expressions that look like
plain ISWIM, but the expressions are more like Simply Typed ISWIM expressions with all of
the type abstractions, type applications, and function argument types erased. An inference
phase in Type-Inferred ISWIM effectively reconstructs the erased types and checks the result.
Thus, a program in Type-Inferred ISWIM is has a type only if the inferencer can both fill in
types and apply the rules of Simply Typed ISWIM.
After we have developed an inferencer for Simply Typed ISWIM, we can get most of the
power of Polymorphic ISWIM by having the inferencer reconstruct Λ abstractions and type
applications.
The techniques and notation used in this chapter are derived from Benjamin Pierce’s
Type Systems for Programming Languages.
M = X
| (λX.M )
| (M M )
| b
| (on M . . . M )
To define type rules Type-Inferred ISWIM expressions, we might take the rules from Simply
Typed ISWIM and omit the type declarations on function arguments:
Γ, X:T ` M : T 0
Γ ` (λx.M ) : (T → T 0 ) ...
The above is a well-defined rule, but it’s not obviously decidable like the Simply Typed ISWIM
rules. In Simply Typed ISWIM, to check a λ expression, a type checker could extend the current
type environment with the declared argument type, check the body expression in the extended
environment, and finally construct a function type using the declared type on the left-hand side
and the body-type on the right-hand side.
Without a declared argument type, a type checker matching the above rule will have to
“guess” a T to use as the argument type. For example,
((λx.x) d 0e )
146 Chapter 16: Type Inference
The expression above could have type num, where the reconstructed type for the x argument is
num. From this simple example, it might appear that the type rule for application can supply
a “guess” to the rule for function by first checking the argument expression, and then using
the resulting type for the function argument. That strategy will not work, however, because
functions can be arguments, too:
((λf.(f d 0e )) (λx.x))
In this example, we cannot type check (λx.x) without guessing num for x. At the same time,
we cannot check (λf.(f d 0e )) without guessing (num → num) for f .
The second example shows that reconstruction in general requires a global view of the
expression being typed. Although the layout of functions and function applications will generate
relationships among the types of expressions, expressions with related types can be arbitrarily
far apart in the source expression. A “magic” type checker could guess locally the right type
for every function variable, so that an overall proof tree fits together, but we need a more
mechanical solution.
The mechanical solution is based on constraint generation and unification. Constraint
generation means that the type rules do not assign a concrete type to exach expression, but
instead generate type names to be resolved later. The rules also generate constraints that
encode relations among different type names. Unification then solves the constraints, assigning
a concrete type to every type name generated by the type rules.
C = a set {T =T, . . .}
X = a set {A, . . .}
The new rule for functions makes type-guessing explicit by generating a new type variable for
the argument:
Γ, X:A ` M : T 0 | C; X
Γ ` (λX.M ) : (A → T 0 ) | C; X ∪ {A} where A 6∈ X
The new rule for function application no longer requires the type of the argument expression
to syntactically match the argument type of the function expression. Instead, the rule finds a
type and set of constraints for each expression, and then combines the constraints with a new
one that enforces the argument-type relationship:
Γ ` M : T1 | C1 ; X1 Γ ` N : T2 | C2 ; X2
Γ ` (M N ) : A | C1 ∪ C2 ∪ {T1 =(T2 → A)}; X1 ∪ X2 ∪ {A}
The condition 6 ∩({X1 , X2 , {A}}) ensures that the type variables generated by the subexpression
are distinct and different from A, so that the constraint sets C1 and C2 can be safely merged
with the new constraint.
The rules for basic constraints and variables are essentially unchanged; they do not generate
constraints or type variables:
Γ ` X : T | ∅; ∅ if Γ(X) = T
Γ ` b : B | ∅; ∅ if B(b) = B
The rule for primitive applications is more complex. Each sub-expression Mi generates a type,
but also a set of constraints and type variables. The overall set of constraints and type variables
includes the ones generated by the sub-expressions, but it also includes constraints mapping
the sub-expressions types to the types expected by the primitive constant.
Γ ` M1 : T1 | C1 ; X1 . . . Γ ` Mn : Tn | Cn ; Xn
Γ ` (on M1 . . . Mn ) : T | C1 ∪ . . . Cn ∪ {T1 =B1 , . . . Tn =Bn }; X1 ∪ . . . Xn
x:α1 ` x : α1 | ∅; ∅
` (λx.x) : (α1 → α1 ) | ∅; {α1 } ` d 0e : num | ∅; ∅
` ((λx.x) 0 ) : α2 | {(α1 → α1 )=(num → α2 )}; {α1 , α2 }
d e
this derivation does not quite provide a type for the expression. Instead, it provides the “type”
α2 with the constraint (α1 → α1 )=(num → α2 ). Since the constraints require α1 to be num and
α2 to be α1 , we can easily see that α2 is num.
The derivation for our second example is somewhat more involved:
By considering the resulting constraints carefully, we can see that α4 must be num, which is
what we expected. But, although we can see α4 must be num, our goals is to make an type
checker extract this result. The unification phase of our checker serves that role.
16.1.2 Unification
The unification phase of our type checker takes the constraints generated by the rules in the
previous subsection and solve them. The unification process is similar to solving for variables
in a set of algebra equations. For example, given the algebra equations
x + y = 16
x + 3y = 8
148 Chapter 16: Type Inference
we can derive x = 16 − y from the first equation, then substitute 16 − y for x in the second
equation. Manipulations on the second equation then yield y = −4, which we can substitute
back into 16 − y to get x = 20.
For the analogous resolution of type constraints, we need a way to pull out equations to sim-
plify the constraint set, plus a way to keep track of substitutions for the final values of removed
variables. The following mapping U is defined recursively to perform a single simplification step
while building up a result mapping.
The result of U is a sequence of equations , A1 =T1 , . . . An =Tn . In this sequence, T1 is the final
type for A1 . Substituting T1 for A1 in T2 provides the final type for A2 , etc. For example,
taking the constraints generated by ((λx.x) d 0e ):
from which we can immediately extract that α2 is num. Taking the constraints generated by
((λf.(f d 0e )) (λx.x)):
In this case, we can see immediately that α4 is num. By straightforward substitution, we also
find that α1 is (num → num).
In general, the R([ ], ) relation extracts the concrete binding of a type variable from a
sequence produced by U:
The rules for U are not deterministic, because we can resolve variables in any order that we
want, but a mechanical unifier might choose the left-to-right order that we used above. In some
cases, however, no U rule matches, regardless of the chosen variable order. For example, if we
generate the constraints for half of Ω:
x:α1 ` x : α1 | ∅; ∅ x:α1 ` x : α1 | ∅; ∅
x:α1 ` (x x) : α2 | {α1 =(α1 → α2 )}; {α2 }
` (λx.(x x)) : (α1 → α2 ) | {α1 =(α1 → α2 )}; {α1 , α2 }
16.2 Inferring Polymorphism 149
we end up with the constaint set {α1 =(α1 → α2 )}, which does not match any of the U rules.
This result is expected: Ω has no type in Simply Typed ISWIM, not even if a mechanical
process is guessing the type.
In other cases, the constraints and rules for U do not completely determine a concrete type
for an expression. Consider the expression (λx.x):
x:α1 ` x : α1 | ∅; ∅
` (λx.x) : (α1 → α1 ) | ∅; {α1 }
The result type is (α1 → α1 ). This result is consistent our experience with polymorphic types:
the identity function can have any type it needs, depending on the context. Without a context,
we are free to choose any value of α1 taht we’d like.
Nevertheless, Type-Inferred ISWIM does not infer a polymorphic type for (λx.x). In the
context
((λf.(f (λy.y)) (f d 0e )) (λx.x))
the type for f will have to be unified with both (num → T1 ) and ((T3 → T3 ) → T4 ). Since num
and (T2 → T3 ) cannot be unified, the expression will have no type.
Exercise 16.2. Show how U solves the constraints generated in Exercise 16.1.
P(T, ∅) = T
P(T, {A} ∪ X ) = P(∀A.T, X ) where A ∈ FV(T )
P(T, {A} ∪ X ) = P(T, X ) where A 6∈ FV(T )
The rule for let uses U, R, and P to assign a type to the let-bound variable.
Γ ` M : T | C1 ; X1 Γ, X:T 0 ` N : T 00 | C2 ; X2
Γ ` (let X = M in N ) : T 00 | C1 ∪ C2 ; X1 ∪ X2 ∪ {A}
The let rule use uses P with only the variables X1 introduced during the checking of M ; the
type expression T may contain other variables that are introduced by the surrounding context,
and those must be resolved later. For the same reason, the let rule propagates the constraints
150 Chapter 16: Type Inference
C1 , which may contain constraints that are relevant to the larger program, even though they
have been resolved once for M . In addition to the useful constraints, C1 may include constaints
that are useless outside of M , but they are also harmless.
Inserting type abstraction with an implicit Λ is only half of the problem. The checker must
also insert implicit type applications. We can add a general rule that converts from polymorphic
types to normal types
Γ ` M : ∀A.T | C; X
Γ ` M : T [A ← A0 ] | C; X ∪ {A0 } where A 6∈ X
Since we are relying on type inference in general, the above rule does not pick a specific A0 ;
unification will find an appropriate type later.
Unfortunately, adding this rule makes the type checker non-deterministic. When checking
a function application and the argument expression has a polymorphic type, when should we
reduce the type with the above rule, and when should we leave it alone? A related problem is
that an expression may have a polymorphic type, but the polymorphic type that is only visible
until after unification. Extending the unifier with polymorphism makes unification “higher-
order,” and much more difficult.
Disallowing polymorphic functions as arguments solves all of these problems. In other
words, a function argument can have a reconstructed type α, but it cannot have reconstructed
type ∀α.T . To enforce this rule, we need only add a restriction to the function and primitive
application rules so that no sub-expression type is of the form ∀A.T . This restriction forces
polymorphic resolution where it is necessary, and ensures that no type expression of the form
∀A.T shows up in a generated constraint.
Applying the polymorphic rules to the example above starts with the following tree
x:α1 ` x : α1 | ∅; ∅ ...
` (λx.x) : (α1 → α1 ) | ∅; {α1 } f :∀α1 .(α1 → α1 ) ` ((f (λy.y)) (f d 0e )) : . . . | . . . ; . . .
` (let f = (λx.x) in ((f (λy.y)) (f d 0e ))) : . . . | . . . ; . . .
If we abbreviate ∀α1 .(α1 → α1 ) with T0 in environments, the top-right subtree will contain a
derivation for (f d 0e ) where f ’s type is instantiated as (α2 → α2 ):
Meanwhile, the derivation for (f (λy.y)) instatiates a different type for f , (α4 → α4 ):
Due to the separate instantiations for f ’s type, the final collection of constraints will have a
solution showing the type of the original expression as num.
151
Throughout our exploration of types so far, we have encountered expressions that could not
be given a type because an equation of the form T1 = . . . T1 . . . could not be solved with a
concrete type for T1 . For example, Ω has no type because T1 = (T1 → T2 ) has no solution for
T1 . The same problem appears with more useful recursive functions that are written in the
style of Chapter 4.
As we saw in Chapter 14, we can add fix to the language to support recursive functions, but
a programmer still cannot write Ω or λ-calculus-style recursive functions directly. For the same
reasons that motivate type inference, we might prefer to type plain ISWIM expressions as much
as possible, including Ω, without forcing a programmer write down type-specific annotations.
Inference for general recursive functions requires a way to solve type constraints of the form
T1 = . . . T1 . . ..
More importantly, recursive type equations show up in data structures as well as functions.
For example, the definition of a list of numbers is inherently recursive:
• null, or
• (cons n l) where n is a number and l is a list of numbers.
We know how to deal with the case split, using disjoint sums, and we can use f for null and
pairs for cons. But the second part of the sum type must be a pair type that refers back to the
entire sum. In other words, the type Listnum must obey the following equation:
Following Chapter 14, we could solve the problem by building lists directly into the type system.
But the more general approach of solving recursive equations is especially valuable to the
programmer in the case of data, as opposed to functions. A recursive function is a recursive
function, but a recursive data structure can have many different shapes: a list, a tree, etc.
Supporting all possible data shapes in the core type rules requires a general form of recursive
types. In this chapter, we study recursive types by extending Polymorphic ISWIM (i.e., we
ignore inference from now on).
Adding tfix to our type language will work, but by convention, a tfix and its following ∀ are
collapsed together into a single µ:
.
Listnum = µα.(bool + (num × α))
152 Chapter 17: Recursive Types
A type constructed with µ is a recursive type. In the same way that f in (fix λf.(λx.(f x))
stands for the entire recursive function within (λx.(f x)), the α above stands for the entire
recursive type within (bool + (num × α)).
As another example, consider the expression:
λx.(+ (x x) d 5e )
Due to the call (x x), The type of x must be a function type. Since the result of the call is
used in an addition expression, the result of the function must be a number. Meanwhile, the
argument of the function must have the same type as the function itself. Thus, the type for x
above is
µα.(α → num)
and the type for the entire function expression is
((µα.(α → num)) → num)
The type for the function shows how µ can appear embedded within a larger type expression.
To support recursive types in general, we extend our grammar for T as follows:
T = ...
| (µA.T )
` T [A ← (µA.T )] ↔ T 0 ` T 0 ↔ T [A ← (µA.T )]
` (µA.T ) ↔ T 0 ` T 0 ↔ (µA.T )
17.3 Isomorphisms Between Recursive Types 153
This equivalence relation lets us unfold a type (µA.T ) by replacing each A in T with (µA.T ).
Unfolding a recursive type can put it into a form that matches another type.
In addition to extending the type-equivalence relation, the function application rule must
allow a µ type for the first sub-expression, instead of an immediate function type. In other
words, instead of requiring the function expression to have type (T 0 → T ), it need only produce
a type that is equivalent to some (T 0 → T ).
Γ ` M : T0 ` T0 ↔ (T 0 → T ) Γ ` N : T 00 ` T 0 ↔ T 00
Γ ` (M N ) : T
Γ ` M : T0 ` T0 ↔ (T 00 → T ) Γ ` N : T 00
Γ ` (M N ) : T
Using the new rules, we can assign a type to half of Ωnum , where r abbreviates (µα.(α → num)):
` (r → num) ↔ (r → num)
x:r ` x : r ` r ↔ (r → num) x:r ` x : r
` (λx:r.(x x)) : (r → num)
To show the type equivalence in the top middle of the tree, we expand the abbreviation r as
(µα.(α → num)), unfold it to ((µα.(α → num)) → num), and re-abbreviate as (r → num).
The rules above define a powerful type system for programming with recursive types. Such
recursive types are call equi-recursive types, because the type rules relate a recursive type
and its unfolded version as equivalent. The main cost of equi-recursive types is that type
checking does not have a straightforward algorithm. When equating recursive types, multiple
` ↔ rules can apply, and a winning strategy for building a complete tree is not always
apparent. Furthermore, combining recursive types with type inference would aggravate the
problem considerably.
M = ...
| (fold M )
| (unfold M )
154 Chapter 17: Recursive Types
V = ... E = ...
| (fold V ) | (fold E)
| (unfold E)
The primary role of fold and unfold is in the type checking rules. We revert the ` ↔
relation back to its simple form, from Chapter 15, as well as the function application rule. All
we need for type checking are two new rules:
Γ ` M : T [A ← (µA.T )] Γ ` M : (µA.T )
Γ ` (fold M ) : (µA.T ) Γ ` (unfold M ) : T [A ← (µA.T )]
Using iso-recursive types, a well-typed half of Ωnum requires a strategically placed unfold
annotation:
λx:(µα.(α → num)).((unfold x) x)
This expression can be typed using the new unfold rule, where r still abbreviates (µα.(α →
num)):
x:r ` x : r
x:r ` (unfold x) : (r → num) x:r ` x : r `r↔r
` (λx:r.((unfold x) x)) : (r → num)
Writing all of Ω requires a fold annotation in addition:
We can use this type macro in defining our expression macros. For example, the cons macro will
be a polymorphic function of type ∀α.(α → (Listα → Listα )). Even null must be polymorphic,
because the null for different kinds of lists will have a different type.
17.4 Using Iso-Recursive Types 155
What should car and cdr do when they are given null as an argument? Our language currently
has no mechanism for signalling errors, and soundness prevents the macros from getting stuck on
bad inputs. One sneaky solution is to loop forever, exploting the fact that Ω can be constructed
to “return” any type of value (see Exercise 14.4).
.
null = Λα.(fold (ToLeftUListα f))
.
cons = Λα.(λv:α.λl:Listα .(fold (ToRightUListα hv, li)))
.
car = Λα.(λl:Listα .(Match(UListα →α) (unfold l)
(λn:bool.Ω[α])
(λp:(α × Listα ).(fst p))))
.
cdr = Λα.(λl:Listα .(Match(UListα →Listα ) (unfold l)
(λn:bool.Ω[Listα ])
(λp:(α × Listα ).(snd p))))
.
isnull = Λα.(λl:Listα .(Match(UListα →bool) (unfold l)
(λn:bool.t)
(λp:(α × Listα ).f)))
.
Ω = Λα.( (λx:(µβ.(β → α)).((unfold x) x))
(fold λx:(µβ.(β → α)).((unfold x) x)) )
The null and cons macros act like ML type constructors, and as expected, they each contain a
fold form. Similarly, the car, cdr, and isnull macros act like deconstructing pattern matches,
so each uses unfold on its argument.
reduces to d 1e , and show that it has type num. To simplify the type derivation, assume that we
have already shown Γ ` Ω[T ] : T for all Γ and T .
156 Chapter 17: Recursive Types
157
Type soundness ensures that applications of primitive operations do not “go wrong” in the sense
that primitive operations are never applied to bad arguments. The information that a program
cannot go wrong is perhaps most useful to a programmer, but language implementors can also
put that information to work. For example, zero and false can be represented in the same
way, without the possibility of strange behavior when false is added to a number. Similarly,
functions can be represented by memory addresses, without the possibility that a number will
be mis-used as the address of a non-existent function.
In other words, types can hide some of the implementation details of a language. The power
to hide implementation details can be useful to programmers, as well as language implementors,
particularly for building modularized software. For example, given our implementation of null
and cons from the previous chapter, we’d prefer that client programmers using cons always use
car to extract the first element of a list, so that we can change the implementation of cons later if
becomes necessary. Such good programming style is not enforced by the type language, however,
at least not for the way we wrote the code in the previous chapter. The type ListT is merely
an abbreviation, and completely transparent to client programmers. Using the expanded type,
a client programmer can manipulate list internals directly, either intentionally or accidentally.
To hide the details of the list type from the programmer, we can force client programmers
to implement list-using code in a particular way: client code must have the type ∀α.T for some
T , where α serves as the type for lists. Since the client code is polymorphic with respect to list
values, the client cannot rely on any implementation details about lists.
This approach to data abstraction can codified through a specific extension of the pro-
gramming language: existential types. Like a universal type ∀A.T , an existential type ∃A.T
describes a value that works with arguments of an unspecified type A. In the case of a univer-
sial type, the unspecified type can be replaced by any type. In the case of an existential type,
the unspecified type can be replaced by only one particular type. That one particular type is
hidden from client programmers, and the type system can enforce the hiding. As well will see,
the difference between ∀A.T and ∃A.T is essentially two levels of procedure indirection.
.
Num1 = num
.
mknum1 = λn:num.n
.
add1 = λn:Num1 .λm:Num1 .(+ n m)
.
parity1 = λn:Num1 .(isodd n)
.
nfuncs1 = hmknum1 , hadd1 , parity1 ii
158 Chapter 18: Data Abstraction and Existential Types
The nfuncs1 tuple bundles the number operations into a tuple that acts like a “library module”
to be supplied to client programmers.
If the base language does not provide bitwise operators (or other operators that can be used
to test for even and odd), then we can optimize the parity test by computing the parity of
the initial numbers, tracking parity during additions, and then extracting the parity value of
the result. Thus, a second implementation of the datatype uses (num × bool) to implement
parity-maintained numbers:
.
Num2 = (num × bool)
.
mknum2 = λn:num.hn, (isodd n)i
.
add2 = λn:Num2 .λm:Num2 .h(+ (fst n) (fst m)), (xor (snd n) (snd m))i
.
parity2 = λn:Num2 .(snd n)
.
nfuncs2 = hmknum2 , hadd2 , parity2 ii
where isodd and xor are defined in the obvious way. (The isodd function will require O(n) time
for an integer n, while xor is constant time.)
Each module-like tuple nfuncsi has type NFuncsNumi where
.
NFuncsT = ((num → T ) × ((T → (T → T )) × (T → bool)))
Instead of supplying the tuple nfuncs1 or nfuncs2 directly to clients, we can hide the specific
implementation type Numi by requiring clients to have the form
∀α.(NFuncsα → T )
In other words, client code must be represented by a polymorphic function that cannot rely on
the details of the number type α. The function consumes a tuple representing the number op-
erations. The body of the function corresponds to the client code proper; it uses the operations
to produce some value of type T .
For example, here is a client that adds 17 and 18, then extracts the parity of the result:
.
client = Λα.λn:NFuncsα (let m:(num → α) = (fst n)
a:(α → (α → α)) = (fst (snd n))
p:(α → bool) = (snd (snd n))
in (p (a (m d 17e ) (m d 18e )))))
where the multiple-variable let macro has the obvious expansion. It extracts the functions of
the “imported module” tuple n into the local variables m, a, and p.
To execute client, we must apply it to one of the implemenations of numbers, either
(client[Num1 ] pfunctions1 )
or
(client[Num2 ] pfunctions2 )
The type system ensures that both applications will work, as long as client has the ∀α . . . type
above (for some specific T ).
If a library implementor provided nfuncs1 or nfuncs2 directly to other programmers, the other
programmers could rely on the type Num1 or Num2 directly, conflicting with a future revision
of the library that changes the implementation type for numbers.
This problem is easily corrected by supplying to programmers a library as a linking proce-
dure, instead of as a tuple. In other words, the library provided by a programmer will combine
nfuncs1 or nfuncs2 with the linking application:
.
ClientT = ∀α.(NFuncsα → T )
.
nlib1 = Λβ.λc:Clientβ .(c[Num1 ] pfunctions1 )
.
nlib2 = Λβ.λc:Clientβ .(c[Num2 ] pfunctions2 )
Note that nlib1 and nlib2 must be parameterized by β, which is the return type of the client
using the library. Given nlib1 or nlib2 , we can link the client program with
or
(nlib2 [bool] client)
The only difference from before is that, given only pfunctioni instead of nfuncsi , the linking
programmer cannot abuse the library by linking it to a client that exploits the concrete type of
numbers. In other words, the type on the c argument of pfunctioni forces clients to respect the
data abstraction.
∃α.NFuncsα
which means “a tuple of three functions involving α, for some hidden type α”. Just as ∀ types
require a creation form (ΛA.M ) and an application form M [T ], ∃ types require a creation and
use form. The creation form is pack:
(pack[A=T ] M as T 0 )
where M generates the value whose reprsentation is to be partially hidden. The variable A will
represent the hidden type, T is the actual hidden type, and T 0 is the type of M where some
instances of T have been replaced by A. The type of the overall pack expression will be ∃A.T 0 .
For example, we can use pack to create our two implementations of numbers as follows:
.
npack1 = (pack[α=Num1 ] nfuncs1 as NFuncsα )
.
npack2 = (pack[α=Num2 ] nfuncs2 as NFuncsα )
160 Chapter 18: Data Abstraction and Existential Types
The type of both expressions is the existiential type we wanted, ∃α.NFuncsα , which in expanded
form is ∃α.((num → α) × ((α → (α → α)) × (α → bool))).
The unpack form uses an abstraction created by pack. While unpacking, it does not expose
the implementation type hidden by pack, but instead declares a local type name to stand for
the hidden type, much like the Λ-bound variable stood for the hidden type in the old encoding:
(unpack[A] X from M in M 0 )
where M 0 produces a packed value, the variable A stands for the hidden type locally, the
variable X recieves the unpacked value produced by M , and the body M 0 uses the unpacked
value polymorphically in A.
For example, to use npack1 , we select a variable γ to stand in place of the unknown type in
client code:
(unpack[γ] n from npack1 in
(let m:(num → γ) = (fst n)
a:(γ → (γ → γ)) = (fst (snd n))
p:(γ → bool) = (snd (snd n))
in (p (a (m 17) (m 18)))))
Since npack1 has type ∃α.((num → α) × ((α → (α → α)) × (α → bool))), the unpack[γ]
expression causes n to have the type ((num → γ) × ((γ → (γ → γ)) × (γ → bool))), which is
consistent with the let bindings. The overall program therefore has type bool.
Note that the body of the unpack expression cannot exploit the concrete representation of
numbers hidden by pack, because the type is reduced to simply γ. Furthermore, if we try to
mix functions from the two packages, as in the following expression, the resulting program has
no type, because γ1 6= γ2 (i.e., no two type variables are ever known to be equal):
(unpack[γ1 ] n1 from nlib1 in
(unpack[γ2 ] n2 from nlib2 in
(let m1 :(num → γ1 ) = (fst n1 )
a1 :(γ1 → (γ1 → γ1 )) = (fst (snd n1 ))
p2 :(γ2 → bool) = (snd (snd n2 ))
in (p2 (a1 (m1 17) (m1 18))))))
Using γ1 for both unpack expressions would not allow the packages to be confused, either. The
γ1 s would be different in the same sense that the xs in (λx.λx.x) are different.
Hiding implies that a value of type ∃α.(α → bool) is by itself useless; since the type
α is unknown, the function cannot be applied to any value. In contrast, a value of type
∃α.((num → α) × (α → bool)) can be useful. The first function in the pair can construct values
of type α, and the second function in the pair can consume those values. The programmer
using such a value need not know anything about the implementation of intermediate value of
type α.
To add existential types to ISWIM to form Existential ISWIM, we extend the expression
grammar with pack and unpack forms, where the pack form generates values.
M = ... T = ...
| (pack[A=T ] M as T ) | (∃A.T )
| (unpack[A] X from M in M )
V = ... E = ...
| (pack[A=T ] V as T ) | (pack[A=T ] E as T )
| (unpack[A] X from E in M )
v = ... ∪ x
18.4 Modules and Existential Types 161
The new type-checking rules assign an existential type to each pack expressions, and require
an existential type for the target of each unpack expressions:
Γ ` M : T [A ← T 0 ] Γ ` T 0 Γ, A ` T
Γ ` (pack[A = T 0 ] M as T ) : ∃A.T
The constraint A 6∈ FV(T ) is needed with the unpack rule to ensure that the introduced variable
A does not escape its scope. Operationally, this constraint implies that a value of an unknown
type for particular unpack expression cannot escape the dynamic extent of the of the unpack
expression (where it would be useless, anyway).
.
add1pack = (unpack[β] n from npack1 in
(let m:(num → β) = (fst n)
a:(β → (β → β)) = (fst (snd n))
in (letf :(β → β) = λx:β.(a x (m d 1e ))
in(pack[α=β] hf, ni as ((α → α) × NFuncsα )))))
Client code can use add1pack in essentially the same way as npack. Of course, we can imagine
other extensions, such as a sub1pack module that adds a subtract-1 operation. The implemen-
tation of sub1pack is the same as add1pack, but with d − 1e instead of d 1e .
What happens if a client wants to use both sub1pack and add1pack? Conceptually, the
program’s achitecture is
npack
% -
add1pack sub1pack
- %
newclient
This program achitecture is known as diamond import, and it demonstrates a problem with
our encoding of modules. When newclient unpacks add1pack, it obtains one type of numbers
162 Chapter 18: Data Abstraction and Existential Types
This expression has no type, because the result of a call to the add-1 function cannot be
provided to the sub-1 function; the types are not compatible. Actually, the representations are
compatible, and the evaluation of (s2 (a1 (m1 d 0e ))) would not get stuck, but the type system
is enforcing too many abstraction boundaries.
We can adjust our encoding of modules to solve this problem. The source of the problem is
that add1pack and sub1pack each separately unpack the original npack. To avoid this unpacking,
we can return to our earlier use of explicit Λ for “clients”, though in this case the two clients serve
as libraries to other clients. Another part of the problem is that both add1pack and sub1pack
re-pack the content of the original npack. In our revised encoding, we will assume instead that
clients of add1pack and sub1pack explicitly import npack to get the base funtionality.
Putting the pieces together, our new definition follows:
.
add1module = Λβ.λn:NFuncsβ .
(let m:(num → β) = (fst n)
a:(β → (β → β)) = (fst (snd n))
in (letf :(β → β) = λx:β.(a x (m d 1e ))
in f )))
The definition of sub1module is similar. The body of the module is simply f because add1module
and sub1module do not introduce any new abstract types. The body of a module that does
introduce a new abstract type would have the form (pack[α=T ] M as (β → β)) for some hidden
type T .
In general, the type of a module will have the shape
where a sequence of βs represents the imported abstract types, the type Tβ... corresponds to
module imports whose types mention the βs, a sequence of αs represents exported abstract
types, and the type Tα...,β... corresponds to a set of exports whose types mention the αs and
βs.
To use add1module and sub1module, a client must link them together with npack:
The main drawback of this approach is readily apparent. As the number of modules that
comprise a program grows, and as modules become more interconnected, the client programmer
is responsible for an increasingly complex linking step to assemble the program. In practice,
this problem can be tempered by staging the linking steps; linking must be delayed only where
diamond imports occur, but completed diamonds can be sealed. But when a library module is
used through a large program, it tends to generate diamonds that are resolved only in the final
linking steps.
163
In all of our typed languages so far, the type of a procedure expression fully determines the
type of the corresponding argument expression in an application. For example, even with type
inference, if M has type (T1 → T2 ) in (M N ), then N must have exactly the type T1 , modulo
the renaming of variables in T1 bound by ∀, µ, or ∃.
A language with subtyping provides more flexibility: the type of N might be exactly T1 ,
or it might be a subtype T10 of T1 . The notion of subtype is defined so that a value whose type
is T10 can replace a value of type T1 without introducing a stuck state.
So far, none of our ISWIM variants have provided an opportunity for subtyping: intuitively,
a value of type bool cannot be used in place of a bool (because an addition might get stuck),
a (num → num) cannot be used in place of a ∀α.(α → α) (because a type application might get
stuck), and a value of type (num × bool) cannot be used in place of a (num × num) (because the
second part of the pair might be used).
A small addition to our language, however, introduces a natural place for subtyping. We
consider the addition of records: tuple values with arbitrary arity, where the fields of the tuple
are labelled. Subtyping naturally arises in the form of records that have structly more fields
than other others.
M = ... E = ...
| hL=M, . . . L=M i | hL=V, . . . L=V, L=E, L=M, . . . L=M i
| M.L
v = ... ∪ l
.
fish = hsize=d 10e i
. .
colorfish = hsize=d 10e , color=redi red = d 3e
If M produces a fish of either sort, we can obtain the fish’s size with M.size.
The type of a record must list the field names of the tuple, and also provide a type for each
field. A field-selection expression requires a record type to the left of the selection dot where
164 Chapter 19: Subtyping
T = ...
| hL:T, . . . L:T i
Γ ` M0 : T 0 . . . Γ ` Mn : T n
Γ ` hL0 =M0 , . . . Ln =Mn i : hL0 :T0 , . . . Ln :Tn i
For example, the type of fish is hsize:numi and the type of colorfish is hsize:num, color:numi.
Using a record type for a function argument, we can define a function that takes a fish and
returns its size:
.
fsize = λf :hsize:numi.f.size
This function has type (hsize:numi → num). Naturally, the expression (fsize fish) has type num,
and it produces the value d 10e when evaluated.
What about (fsize colorfish)? When evaluated, it also produces d 10e . But this expression
has no type, because fsize consumes an argument of type hsize:numi, while colorfish has type
hsize:num, color:numi. Clearly, we want to make hsize:num, color:numi a subtype of hsize:numi,
because (intuitively) replacing fish with colorfish can never cause a program to become stuck.
In general, any record type that has at least the fields of another record type should be a
subtype. To define subtypes formally, we introduce a ≤ relation, where T ≤ T 0 means “T is a
subtype of T 0 .” Initially, we define the relation as follows:
T ≤ T
0
hL0 :T0 , . . . Ln :Tn i ≤ hL00 :T00 , . . . L0m :Tm i
0 0
if {L0 :T0 , . . . Ln :Tn } ⊇ {L0 :T0 , . . . L0m :Tm
0
}
The notation ≤ suggests the following intuition about the meaning of subtyping: the set of
values belonging to a subtype is smaller than the set of values belonging to the original type,
because the latter includes the former.
We also adjust the rule for function application to allow subtypes in the argument position:
Γ ` M : (T 0 → T ) Γ ` N : T 00 T 00 ≤ T 0
Γ ` (M N ) : T
(To correctly handle polymorphism and recursive types, we could adjust our subtyping rule to
absorb the ` ↔ relation, but we ignore the extra complexity.)
Using the new rules, we can show a type for (fsize colorfish), abbreviating num with n, size
with s, and color with c:
f :hs:ni ` f : hs:ni
f :hs:ni ` f.s : n
` (λf :hs:ni.f.s) : (hs:ni → n) ` hs=d 10e , c=redi : hs:n, c:ni hs:n, c:ni ≤ hs:ni
` ((λf :hs:ni.f.s) hs=d 10e , c=redi) : n
We can easily verify that (apply fsize) has a type. Suppose that we have a function that extracts
a fish’s color:
.
cfcolor = λf :hsize:num, color:numi.f.color
Can we use cfcolor as an argument to apply? According to the type system, the answer is “no”,
even though (apply cfcolor) produces a value.
In this case, the type system’s restriction is justified. The body of apply would be well-typed
if the argument of f is changed to fish instead of colorfish. If we made that change and then
applied apply to cfcolor, evaluation would get stuck.
If we really want to apply functions to colorfish, then we should declare a different type on
the argument of apply:
.
capply = λf :(hsize:num, color:numi → num).(f colorfish)
Again, we can easily verify that (capply cfcolor) has a type. But now (capply fsize) has no type,
although it still produces a value.
In this case, the type system is too restrictive. Since every function on fishes works on color
fishes, capply should accept both kinds of functions. There is no one type we can write for
capply’s argument, but we can extend our subtyping relation. Again, every function on fishes
works on color fishes, which means that the type of a function on fishes should be a subtype of
a function on colorfishes:
At first glance, this relation may look backward, but it is not. Intuitively, a color fish is a
special kind of fish, but a function on fishes is a special kind of function on color fishes. Put
another way, the set of fishes is larger than the set of color fishes (because the former includes
the latter), and the set of functions that work on color fishes is larger than the set of functions
that work on fishes (because the former includes the latter).
In general, a subtype relation for the argument part of a function type induces the reverse
relation on the function type as a whole. A position in type expression with this property is
called a contra-variant position.
Before we define the general subtyping rule on function types, consider the result position.
Suppose a function returns a color fish; can it be used in place of a function that returns a fish?
Yes, just as a color fish can be used in place of a fish. This less surprising kind of position is
called co-variant: a subtype relation in the result position of a function type induces the same
subtype relation in the function type as a whole.
Thus, the general rule for function subtyping is as follows:
T10 ≤ T1 T2 ≤ T20
(T1 → T2 ) ≤ (T10 → T20 )
Using this new rule, we can show a type for (capply fsize):
Should we be able to use a school composing two color fish as a school of plain fish?
.
cschool = hone=hsize:1, color:redi, two=hsize:1, color:blueii
Yes. A school of color fish clearly works wherever a school of fish works, because the only
possible operation on a school is to extract its fish, and the fish are individually replaceable
with color fish.
More generally, we can allow subtypes on fields within records co-variantly.
As it turns out, few realistic programming languages support this kind of subtyping. The reason
is that such languages tend to provide an additional operation on records: field update. When
field update is allowed along with subtyping on record fields, a field might get replaced with a
super type value. For example, a color school might be used as a plain school, and then the one
field of the school could be updated with a fish (not a color fish). Other parts of the program
that expect a color school will then find a plain fish in the school, and probably get stuck as a
result.
To support update operations, record fields in a typical language are invariant, which
means that they are neither co-variant nor contra-variant. In particular fields of an object in
Java are invariant, as we will see in the next chapter.
To call the getsize “method” of fishobj, we extract the getsize procedure from fishobj and apply
it to fishobj:
(fishobj.getsize fishobj)
This expression has a type and produces the expected result.
A more realistic encoding of objects requires a more precise type for the argument to getsize.
In particular, methods must be mentioned in the type of s so that the body of the method can
call the object’s own methods—including the getsize method. Such a refinement is possible
with recursive types, but we ignore this generalization, because we encounter a problem even
with the simple encoding.
To see the problem, consider a color fish with a getsize method where the fish’s color
multiplies its apparent size:
.
colorfishobj = hsize=d 10e , color=d 2e , getsize=λs:hsize:num, color:numi.(∗ s.size s.color)i
167
Again, the expression for calling getsize of colorfishobj has a type and value:
(colorfishobj.getsize colorfishobj)
(colorfishobj.getsize fishobj)
should not have a type, because it will get stuck; fishobj will not have the color field that getsize
wants.
The final example not only shows that the encoding should fail, but it shows why: a pro-
grammer can construct bad “method calls” where the wrong self object is supplied to the
method. Following our earlier strategy for addressing type problems, we can solve this one by
treating methods differently than fields, and by not allowing method-as-field accesses except
those that fit the right pattern. We explore this path in the next chapter.
168 Chapter 19: Subtyping
169
In an untyped setting, we can easily model classes and objects by using λ to construct methods
and pairs or records to construct objects. However, as we saw in the previous chapter, such
an encoding of objects does not work well with the type system of Simply Typed ISWIM or
its variants. In the same way that adding pairs to Simply Typed ISWIM was the simplest way
of obtaining well-typed pairs, adding classes and objects to the language—or starting with an
entirely new language based on classes—is the simplest and usually most useful way of obtaining
well-typed objects.
In this chapter, we abandon ISWIM and model directly an object-oriented language. In
particular, we model a subset of the JavaTM language. Java itself is far too large to model
formally in the space of a modest textbook. We choose a subset that contains the programming
elements we are most interested in, which in this case include classes, objects, fields, methods,
inheritance, overriding, and imperative field update. We ignore interfaces, abstract methods,
exceptions, and arrays.
P = ĉ . . . ĉ M a program
The only expression forms are field access, field update, method calls, super calls, and casts.
M = X
| null
| new c
| M :c.f field access
| M :c.f := M field assignment
| M.m(M, . . . M ) method call
| super X:c.m(M, . . . M ) super call
| (c)M cast
| b
| (on M . . . M )
T = c
| B
b = a basic constant
on = an n-ary primitive operation
B = a basic type
170 Chapter 20: Objects and Classes
In the case of field accesses and updates, the field name is annotated with its source class, so
that we can ignore the problem of field hiding in derived classes. Similarly, for super calls, the
target object as a variable (usually this) and the superclass are named explicitly. Instead of
modeling object constructors, every field in an object is initialized to a given constant, which
must be null for class-typed fields. As usual, we assume an unspecified set of basic constants
b, primitive operations on , and basic types B. The set of types T includes basic types and class
names.
The following example program defines a fish class and a derived colorfish class, and then
instantiates both classes:
The fish class contains the field size and the methods getWeight, grow, and eat. The getWeight
method returns the value of the size field in this. The grow method increments the size field
of this, and the eat method calls grow with the weight of the given fish. The colorfish class
adds a color field, and overrides the getWeight method. The overriding declaration chains to
fish’s getWeight and multiplies the result by the fish’s color.
A well-formed MiniJava program must obey certain high-level constraints: every class name
must be declared only once, the built-in class Object must not be declared, the fields of each
class must be unique, the methods of each class must be unique, and every class that is used
must be declared. These properties are most easily captured by relations defined with “is
in”, which relates arbitrary symbol sequences, and with “· · ·”, which stands for an arbitrary
sequence of symbols with balanced braces and parentheses.
ClassesOnce(P ) iff
(class c · · · class c0 is in P ) implies c 6= c0
ObjectBuiltin(P ) iff
class Object is not in P
FieldsOncePerClass(P ) iff
(class c extends c0 {· · · T1 f1 · · · T1 f2 · · ·} is in P ) implies f1 6= f2
MethodsOncePerClass(P ) iff
(class c extends c0 {· · · T1 m1 · · · T1 m2 · · ·} is in P ) implies m1 6= m2
ClassesDefined(P ) iff
(c is in P ) implies c = Object or (class c is in P )
By inspecting the fish example, we can easily see that all of these relations hold for the example
program.
Besides these basic checks, the declared class must form an inheritance tree (as opposed to
a cyclic inheritance graph!), overriding method declarations must be consistent with superclass
method definitions, and so on.
We can simplify the checking of such properties by defining a few more derived relations
20.1 MiniJava Syntax 171
with “is in”. For example, ≺P relates a class and its declared superclass in P .
c ≺P c0 iff
class c extends c0 is in P
∈fP c iff
hc.f, T, V i ∈
class c extends c0 {· · · T f = V · · ·} is in P
∈m
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈ P c iff
0
class c extends c {· · · T0 m(T1 X1 , . . . Tn Xn ){ M } · · ·} is in P
In the earlier example, fish ≺P Object, colorfish ≺P fish, hcolorfish.color, num, d 7e i ∈∈fP colorfish,
and hgrow, (num → num), (a), (+ a this:fish.size)i ∈∈m P fish.
The transitive closure of the ≺P relation is the complete subclass relation ≤P , which must be
antisymmetric so that inheritance is well-defined (i.e., the subclass relationship among classes
must form a tree):
≤P = transitive–reflexive closure of ≺P
WellFoundedClasses(P ) iff ≤P is antisymmetirc
Using the ≤P relation, we can define the final field-inclusion relation, where a class inherits the
fields of its superclass, and also check that method overriding preserves the type of a method.
Thus, hfish.size, num, d 1e i ∈fP fish and hfish.size, num, d 1e i ∈fP colorfish.
For the purposes of type checking, we could define a method-inclusion relation like the one
for fields:
0
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈m P c iff
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈∈P c and c0 ≤P c
m
However, in the case that a method is overriden, this definition assigns multiple method imple-
mentations to a given class for the method name. A more useful relation would pick the most
overriding implementation of the method, i.e., the one from the minimum class (according to
the ≤P relation) that defines the method.
0
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈m
P c iff
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈∈mP c
and c = min{c | c0 ≤P c and hm, (T10 . . . Tn0 → T00 ), (X10 , . . . Xn0 ), M 0 i ∈
∈mP c}
E = []
| E:c.f
| E:c.f := M
| V :c.f := E
| E.m(M, . . . M )
| V.m(V, . . . V, E, M, . . . M )
| super V :c.m(V, . . . V, E, M, . . . M )
| (c)E
| (on V . . . V E M . . . M )
An object in the store hT, FSi consists of a class tag T , which indicates the class instantiated
by the object, and a mapping FS from class-prefixed field names to values. The class tag is
needed for method dispatch and for casts.
The tag is only meaningful in the context of the program P ; the evaluation rules combine the
tag with static information derived from P . In addition, the program P determines the fields
to create for a new T expression. Thus, the reduction rules have the form P ` M 7−→mj M 0
to expose the dependence on the (static) program P .
Given the above reduction rules, the evalution of an expression can get stuck in many ways.
For example, a field access can fail because the field does not exist in the object, a method call
20.3 MiniJava Type Checking 173
can fail because the method is not present, a cast can fail because the object is not an instance
of the specified type, or the target of an object operation can be null.
In the next section, we develop type rules that eliminate many of the stuck states, but the
type rules will not be able to avoid all of them. For example, the type system will not reject
programs that (eventually) call a method of null. Also, if the cast operation is to be useful in
the same way that Java’s cast is useful, the type system cannot prevent cast failures.
We can nevertheless define a sound language by adding rules that signal errors in certain
cases, but rely on type checking to avoid other kinds of errors. In other words, soundness
does not mean that errors are impossible, but that certain kinds of errors are impossible. For
an object-oriented language like Java, the kinds of errors that soundness should preclude are
“message not understood” errors (i.e., no such method or field) for non-null objects.
The error rules that we add to MiniJava are analogous to run-time exceptions in the real
Java language. They are not “message not understood” errors, but instead handle null and
cast failures.
Exercise 20.1. Suppose that MiniJava is sound (using the type rules developed in the next
section), but we replace the rule
with
P ` hE[(c)null], Σi 7−→mj herror: bad cast, Σi
Is the revised MiniJava still sound? Which of the above rules most closely matches true Java
evaluation?1
Exercise 20.2. Show the evaluation of the fish example program’s expression in Section 20.1.
P `d ĉ1 . . . P `d ĉn P, `e M : T
`p P
where P = ĉ1 . . . ĉn M, ClassesOnce(P ),
ObjectBuiltin(P ), FieldsOncePerClass(P ),
MethodsOncePerClass(P ), ClassesDefined(P ),
WellFoundedClasses(P ),
and OverridesConsistent(P )
Checking a declaration with P `d requires checking the declared class’s fields with P `f and
methods with P, `m . The extra information to the left of ` in P, `m supplies a type for
this.
Checking a field with P `f consists of checking the initial value expression (in the empty
environment) to ensure that it has the declared type:
P, `e V : T
P `f T f = V
Checking a method with P, `m consists of checking the body expression of the method. The
environment of the body expression provides a type for this and for each formal argument.
For reasons explained further below, we use P, `s : to check the body expression’s type
instead of P, `e : .
P, Γ `e M : c0 P, Γ `e M : c0 P, Γ `s M 0 : T
P, Γ `e M :c.f : T P, Γ `e M :c.f := M 0 : T
where hc.f, T, V i ∈fP c0 where hc.f, T, V i ∈fP c0
P, Γ `e M : c P, Γ `s M1 : T1 . . . P, Γ `s Mn : Tn
P, Γ `e M.m(M1 , . . . Mn ) : T0
where hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M0 i ∈m
P c
P, Γ `s M1 : T1 . . . P, Γ `s Mn : Tn
P, Γ `e super X:c.m(M1 , . . . Mn ) : T0
where Γ(X) = c0 , c0 ≺P c
and hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈m
P c
P, Γ `e M : c0
P, Γ `e (c)M : c P, Γ `e b : B where B(b) = B
P, Γ `e M1 : B1 . . . P, Γ `e Mn : Bn
P, Γ `e (on M1 . . . Mn ) : B where ∆(on ) = hhB1 , . . . Bn i, Bi
20.4 MiniJava Soundness 175
Many of the P, `e : rules use the subsumption rule P, `s : , which allows the actual
type of an expression to be a subclass of a target class type:
P, Γ `e M : c0 P, Γ `e M : B
P, Γ `s M : c P, Γ `s M : B
where c0 ≤P c
Exercise 20.3. Show that following program’s expressions are well-typed (i.e., show the P, `e
: subtrees of the type derivation for the program):
Exercise 20.4. Show that the fish example program in Section 20.1 is well-typed.
• P ` hM, ∅i 7−→
→mj hV, Σi for some V and Σ; or
→mj hM, Σi implies P ` hM, Σi 7−→mj hM 0 , Σ0 i; or
• P ` hM, ∅i 7−→
• P ` hM, ∅i 7−→
→mj herror: dereferenced null, Σi for some Σ; or
• P ` hM, ∅i 7−→
→mj herror: bad cast, Σi for some Σ.
We can prove soundness in essentially the same way as for Simply Typed ISWIM, but with one
important twist: intermediate steps in a MiniJava program contain store addresses as well as
normal expressions.
Our type rules so far do not provide a type for a σ expression, because σ never appears in
Γ. For any point in evaluation, the appropriate type for a σ depends on its mapping in the
store; if σ maps to an object hc, FSi, then the appropriate type is c.
To type an intermediate program, therefore, we must construct an environment that maps
each of the current σs to a class type, such that the environment is consistent with the store.
In addition, the objects in the store must have field values that are consistent with the declared
type of the field. To track these requirements, we define environment–store consistency as
176 Chapter 20: Objects and Classes
follows:
Γ P Σ iff
Σ(σ) = hc, FSi implies Γ(σ) = c 1
and dom(FS) = {c.f | hc.f, T, V i ∈fP c} 2
and FS(c.f ) = σ 0 and hc.f, T, V i ∈fP c 3
implies Σ(σ 0 ) = hc0 , FS 0 i and c0 ≤P T
and hc.f, B, V 0 i ∈fP c 4
implies FS(c.f ) = b and B(b) = B
and dom(Γ) ⊆ dom(Σ) 5
The first and last constraints, 1 and 5 , ensure that Σ and Γ map the same addresses. The
first four constraints verify each object in the store: the Γ mapping of the object should be
the object’s class ( 1 ); all of the fields should be intact ( 2 ); object-valued fields contain
objects in the store of an appropriate type ( 3 ); and basic-typed fields contain constants of
the appropriate type ( 4 ).
As usual, we need a few simple lemmas to prove soundness:
Lemma 20.2: If `p P and P, Γ `e E[M ] : T then P, Γ `e M : T 0 for some T 0 .
The proof of the above lemmas follows by induction on the structure of E. Note that no expres-
sion form in E extends the environment, so the same Γ is used for checking all subexpressions
of a particular expression.
Since MiniJava supports subsumption, our soundness proof requires a stronger lemma than
Lemma 20.3:
Lemma 20.5: If `p P , P, Γ `e E[M ] : T , P, Γ `e M : c, P, Γ `e M 0 : c0 , and
c0 ≤P c, then P, Γ `s E[M 0 ] : T .
• Base case:
– Case E = [ ]
Since c0 ≤P c, P, Γ `s M 0 : c.
• Inductive cases; for each sub-context E 0 in the cases below, P, Γ `e E 0 [M ] : T 0
for some T 0 by Lemma 20.2, and by induction P, Γ `s E 0 [M 0 ] : T 0 . If T 0 is a
basic type, then P, Γ `e E 0 [M 0 ] : T 0 , and the claim will hold by Lemma 20.3.
Otherwise, T 0 = c1 and P, Γ `e E 0 [M 0 ] : c2 for some c1 and c2 such that
c2 ≤P c1 .
– Case E = E 0 :c00 .f
If hc00 .f, T, V i ∈fP c1 , then hc00 .f, T, V i ∈fP c2 by the definition of ∈fP . Thus,
P, Γ `e E[M 0 ] : T .
– Case E = E 0 :c00 .f := M0
Analogous to the previous case.
– Case E = V :c00 .f := E 0
Since P, Γ `e V :c00 .f := E 0 [M ] : T , P, Γ `s E 0 [M ] : T , which means
that c1 ≤P T . By transitivity, c2 ≤P T , so P, Γ `s E 0 [M 0 ] : T . Thus,
P, Γ `e V :c00 .f := E 0 [M 0 ] : T .
20.4 MiniJava Soundness 177
– Case E 0 .m(M, . . . M )
Similar to the field access case, using the definition of ∈m
P , plus the OverridesConsistent(P )
portion of `p P .
– Case V.m(V, . . . V, E 0 , M, . . . M )
Similar to the field assignment case where E 0 is on the right-hand side; the
use of P, `s : for method arguments means that the overall type is the
same for M or M 0 .
– Case super V :c.m(V, . . . V, E 0 , M, . . . M )
Analogous to the previous case.
– Case (c)E 0
Since E[M 0 ] has a class type, the type of the cast expression is the same
with M or M 0 .
– Case (on V . . . V E M . . . M )
The type of E[M 0 ] cannot be a class type.
By Lemma 20.5,
Exercise 20.5. Suppose that we extend MiniJava with a Java-like instanceof operator:
(M instanceof c)
For simplicity, assume that b includes suitable return values for instanceof, bt and bf , and
that B contains a corresponding element Bb such that B(bt ) = Bb and B(bf ) = Bb . The type
rule for the new form is
P, Γ `e M : c0
P, Γ `e (M instanceof c) : Bb
Define new reduction rules to handle instanceof, and describe the proof modifications needed
to demonstrate soundness for the extended language.
20.5 MiniJava Summary 181
M = X
| null
| new c
| M :c.f field access
| M :c.f := M field assignment
| M.m(M, . . . M ) method call
| super X:c.m(M, . . . M ) super call
| (c)M cast
| b
| (on M . . . M )
| σ
T = c
| B
V = b
| null
| σ
E = []
| E:c.f
| E:c.f := M
| V :c.f := E
| E.m(M, . . . M )
| V.m(V, . . . V, E, M, . . . M )
| super V :c.m(V, . . . V, E, M, . . . M )
| (c)E
| (on V . . . V E M . . . M )
FS = a function {hc.f, V i, . . .}
Σ = a function {hσ, FSi, . . .}
182 Chapter 20: Objects and Classes
Information-Gathering Relations
ClassesOnce(P ) iff
(class c · · · class c0 is in P ) implies c 6= c0
ObjectBuiltin(P ) iff
class Object is not in P
FieldsOncePerClass(P ) iff
(class c extends c0 {· · · T1 f1 · · · T1 f2 · · ·} is in P ) implies f1 6= f2
MethodsOncePerClass(P ) iff
(class c extends c0 {· · · T1 m1 · · · T1 m2 · · ·} is in P ) implies m1 6= m2
ClassesDefined(P ) iff
(c is in P ) implies c = Object or (class c is in P )
WellFoundedClasses(P ) iff
≤P is antisymmetirc
OverridesConsistent(P ) iff
∈m
(hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈ P c1 )
and (hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M 0 i ∈
0 0 0 0 0
∈m P c2 )
implies (c1 6≤P c2 or (T1 . . . Tn → T0 ) = (T1 . . . Tn0 → T00 ))
0
c ≺P c0 iff
class c extends c0 is in P
∈fP c iff
hc.f, T, V i ∈
class c extends c0 {· · · T f = V · · ·} is in P
∈m
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈ P c iff
0
class c extends c {· · · T0 m(T1 X1 , . . . Tn Xn ){ M } · · ·} is in P
0
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈m
P c iff
∈m
hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈ P c
and c = min{c | c0 ≤P c and hm, (T10 . . . Tn0 → T00 ), (X10 , . . . Xn0 ), M 0 i ∈∈m
P c}
20.5 MiniJava Summary 183
Reductions
Type Rules
P `d ĉ1 . . . P `d ĉn P, `e M : T
`p P
where P = ĉ1 . . . ĉn M, ClassesOnce(P ),
ObjectBuiltin(P ), FieldsOncePerClass(P ),
MethodsOncePerClass(P ), ClassesDefined(P ),
WellFoundedClasses(P ),
and OverridesConsistent(P )
P, Γ `e M : c0 P, Γ `e M : c0 P, Γ `s M 0 : T
P, Γ `e M :c.f : T P, Γ `e M :c.f := M 0 : T
where hc.f, T, V i ∈fP c0 where hc.f, T, V i ∈fP c0
P, Γ `e M : c P, Γ `s M1 : T1 . . . P, Γ `s Mn : Tn
P, Γ `e M.m(M1 , . . . Mn ) : T0
where hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M0 i ∈m
P c
P, Γ `s M1 : T1 . . . P, Γ `s Mn : Tn
P, Γ `e super X:c.m(M1 , . . . Mn ) : T0
where Γ(X) = c0 , c0 ≺P c
and hm, (T1 . . . Tn → T0 ), (X1 , . . . Xn ), M i ∈m
P c
P, Γ `e M : c0
P, Γ `e (c)M : c P, Γ `e b : B where B(b) = B
P, Γ `e M1 : B1 . . . P, Γ `e Mn : Bn
P, Γ `e (on M1 . . . Mn ) : B where ∆(on ) = hhB1 , . . . Bn i, Bi
P, Γ `e M : c0 P, Γ `e M : B
P, Γ `s M : c P, Γ `s M : B
where c0 ≤P c
Bibliography
[2] H. P. Barendregt. The Lambda Calculus: Its Syntax and Semantics. North Holland, 1984.
[3] D. R. Chase. Safety considerations for storage allocation optimizations. In Proc. ACM
Conference on Programming Language Design and Implementation, pages 1–10, 1988.
[4] W. D. Clinger. Proper tail recursion and space efficiency. In Proc. ACM Conference on
Programming Language Design and Implementation, pages 174–185, 1998.
[5] P. J. Landin. The mechanical evaluation of expressions. The Computer Journal, 6(4):308–
320, 1964.
[6] G. Morrisett, M. Felleisen, and R. Harper. Abstract models of memory management. In
Proc. Conference on Functional Programming Languages and Computer Architecture, 1995.
[7] G. D. Plotkin. Call-by-name, call-by-value, and the lambda calculus. Theoretical Computer
Science, 1:125–159, 1975.
185
Index
186
187
reflexive–symmetric–transitive closure, 11
relation, 10
tail calls, 85
tail recursion, 85
textual machine, 53
transitive, 10
type inference, 145
type reconstruction, 145
type relation, 122
type system, 122
Type-Inferred ISWIM, 145
typed language, 122
types, 122
unfold, 153
unification, 146
universal types, 142
untyped language, 122
values, 42
variants, 137
Y combinator, 34