本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
5The Lambda Calculus and Operational Semantics
The interpreter of the last chapter defines Moor: whatever it does is what a Moor program means. That is a fine definition for running programs and a poor one for reasoning about them, since to know what x + 1 means one must read a few hundred lines of Rust. This chapter takes the opposite road. It starts from the smallest language that can compute anything, with one way to build a function and one way to call it, and then writes the meaning of a richer language as a handful of rules, each one line, from which an interpreter can be read off.
5.1 Terms and substitution
You already know
A closure is a function value that carries the variables it uses from its surrounding scope; a higher-order function takes or returns functions (Year 2 volume). Structural induction proves a property of every tree by proving it for each kind of node, assuming it for the children (Year 1 volume). In a formula , the quantifier binds the occurrences of in ; the others are free (Year 2 volume, predicate logic).
Definition 5.1 (-term)
The -terms over a set of variables are given by the grammar . A term is an abstraction: the function that maps to . A term is an application: the function called with the argument .
Application associates to the left, so is , a function of two arguments taken one at a time; and the body of a extends as far right as possible, so is . In code we write \x. M for , and \x y. M for . A binds its variable in its body exactly as a quantifier does in logic: in the occurrence of is bound and is free, and the free variables of a term are defined by the same structural recursion as for formulas.
Definition 5.2 (-equivalence, capture-avoiding substitution)
Two terms are -equivalent if they differ only in the names of bound variables, renamed consistently: and are, and are not. The capture-avoiding substitution replaces the free occurrences of in by , after renaming the bound variables of that would otherwise capture a free variable of .
Capture is the whole difficulty. Substituting for in naively gives , the identity, where we wanted the function that ignores its argument and returns . The correct result renames first: . Terms are considered up to -equivalence from now on, so this renaming is harmless.
Names make implementations fragile: every substitution must check for capture and invent fresh names. Nicolaas de Bruijn removed the names altogether.
Definition 5.3 (de Bruijn index)
In the de Bruijn notation, a bound variable is replaced by the number of ’s between its occurrence and its binder: 0 for the nearest enclosing , 1 for the next one out, and so on. The term becomes .
Two -equivalent terms have the same de Bruijn form, so -equivalence becomes plain equality of trees. Listing 5.1 is the representation used in this chapter: an index for a bound variable, a name for a free one, and the binder’s name kept only as a hint for printing.
#[derive(Clone, Debug)]
pub enum Term {
Var(usize),
Free(String),
Lam(String, Box<Term>),
App(Box<Term>, Box<Term>),
}
use Term::*;
pub fn lam(x: &str, b: Term) -> Term {
Lam(x.to_string(), Box::new(b))
}
pub fn app(f: Term, a: Term) -> Term {
App(Box::new(f), Box::new(a))
}
/// alpha-equivalence is equality of de Bruijn terms: names do not count.
pub fn alpha_eq(a: &Term, b: &Term) -> bool {
match (a, b) {
(Var(i), Var(j)) => i == j,
(Free(x), Free(y)) => x == y,
(Lam(_, p), Lam(_, q)) => alpha_eq(p, q),
(App(f, x), App(g, y)) => alpha_eq(f, g) && alpha_eq(x, y),
_ => false,
}
}
Substitution must now keep indices right. When a term is substituted under a , its free indices must grow by one, since they now cross one more binder: this is the shift. And when a disappears in a reduction, the indices that pointed past it must shrink by one. Listing 5.2 does both.
/// Add d to every index that points outside the term (at or above `cut`).
pub fn shift(d: isize, cut: usize, t: &Term) -> Term {
match t {
Var(k) if *k >= cut => Var((*k as isize + d) as usize),
Var(k) => Var(*k),
Free(x) => Free(x.clone()),
Lam(x, b) => Lam(x.clone(), Box::new(shift(d, cut + 1, b))),
App(f, a) => App(Box::new(shift(d, cut, f)), Box::new(shift(d, cut, a))),
}
}
/// t[j := s]: under each lambda, j and the free indices of s grow by one.
pub fn subst(j: usize, s: &Term, t: &Term) -> Term {
match t {
Var(k) if *k == j => s.clone(),
Var(k) => Var(*k),
Free(x) => Free(x.clone()),
Lam(x, b) => Lam(x.clone(), Box::new(subst(j + 1, &shift(1, 0, s), b))),
App(f, a) => App(Box::new(subst(j, s, f)), Box::new(subst(j, s, a))),
}
}
/// (\x. body) arg -> body[x := arg], the lambda removed.
pub fn beta(body: &Term, arg: &Term) -> Term {
shift(-1, 0, &subst(0, &shift(1, 0, arg), body))
}
5.2 Reduction
Definition 5.4 (-reduction, redex, normal form)
A redex is a subterm of the form . -reduction replaces one redex by , anywhere in a term; we write for one step and for zero or more. A term with no redex is in normal form.
The term reduces in one step to , renaming to avoid capture. Some terms have no normal form: reduces to itself, forever. And a term with several redexes may be reduced in several orders, which is where the choices of a programming language begin.
Definition 5.5 (Evaluation strategy)
An evaluation strategy chooses which redex to reduce next. Normal-order reduction reduces the leftmost outermost redex, also under a . Call by name does the same but never reduces under a or inside an argument. Call by value reduces a redex only once is a value (here, an abstraction), and never under a . Lazy evaluation (call by need) is call by name in which an argument, once evaluated, is shared by all the places that use it.
Listing 5.3 implements four strategies: the three above and applicative order, leftmost innermost, which reduces arguments first and also goes under ’s; it is call by value continued to a normal form. Each step returns the new term, or nothing when the strategy finds no redex.
pub fn step(t: &Term, s: Strategy) -> Option<Term> {
use Strategy::*;
match t {
Var(_) | Free(_) => None,
Lam(x, b) => match s {
Normal | Applicative => step(b, s).map(|b| Lam(x.clone(), Box::new(b))),
ByName | ByValue => None,
},
App(f, a) => {
let redex = |f: &Term| if let Lam(_, b) = f { Some(beta(b, a)) } else { None };
match s {
Normal | ByName => redex(f).or_else(|| match step(f, s) {
Some(f2) => Some(App(Box::new(f2), a.clone())),
None if s == Normal => step(a, s).map(|a2| App(f.clone(), Box::new(a2))),
None => None,
}),
ByValue | Applicative => {
if s == Applicative || !is_value(f) {
if let Some(f2) = step(f, s) {
return Some(App(Box::new(f2), a.clone()));
}
}
if s == Applicative || !is_value(a) {
if let Some(a2) = step(a, s) {
return Some(App(f.clone(), Box::new(a2)));
}
}
redex(f)
}
}
}
}
}
The reduction graph below shows every way to reduce one small term. Each strategy is one path through it; they differ in length, and call by name even stops early, at a term whose head is the free variable , since it never reduces inside an argument.
reduction_graph_of_the_figure enumerates them: six terms, seven arrows). Normal order copies the unreduced argument and reduces it twice; call by value reduces it once, before the copy.Every path that ends, ends at . This is no accident of the example. To say why, we step back to rewriting in general.
Definition 5.6 (Term rewriting system, confluence)
A rewriting system is a set with a relation on it, often given by rules that rewrite terms (a term rewriting system); is its reflexive transitive closure. The system is confluent if whenever and , there is a with and ; locally confluent if this holds whenever and in one step each; terminating if there is no infinite chain .
Theorem 5.7 (Church–Rosser)
-reduction is confluent.
Proof. Admitted at this level. ∎
Local confluence is not enough here, since -reduction does not terminate, and a one-step diamond fails: reducing a redex inside an argument that is copied twice must be repeated in both copies. The usual proof defines a parallel reduction that contracts any set of redexes at once, shows by induction on terms that it satisfies the one-step diamond, and notes that its reflexive transitive closure is .
Corollary 5.8
A -term has at most one normal form, up to -equivalence.
Proof. If and with both in normal form, confluence gives with and . A normal form reduces only to itself, so . ∎
So the strategies cannot disagree on the result; they can only disagree on whether they reach it. Normal order is the safe one.
Theorem 5.9 (Normal order normalises)
If a -term has a normal form, normal-order reduction reaches it.
Proof. Admitted at this level. ∎
The proof goes through the standardisation theorem: any reduction to a normal form can be reordered so that it contracts redexes from left to right, outermost first. It is longer than this chapter allows; we use the result and check it on examples. Applicative order is the fragile one: in it reduces forever, while normal order discards it in one step (exercise 5.11).
For a terminating system, local confluence is all one needs to check, because of a lemma whose proof is a model of well-founded induction.
Lemma 5.10 (Newman)
A terminating, locally confluent rewriting system is confluent.
Proof. Since the system terminates, the relation “ is reachable from in at least one step” has no infinite chain, so we may prove a property of all elements by induction along it: assume the property for every element reachable from in one or more steps, and prove it for . The property is: every two reducts of have a common reduct.
Let and . If either reduction is empty, say , take . Otherwise write and . By local confluence, there is with and . Now is a reduct of , so the induction hypothesis applies to it: and , both reducts of , have a common reduct . Likewise is a reduct of , and and are both reducts of (since ), so they have a common reduct . Then and . ∎
Termination is usually proved by a measure: a function to the natural numbers that every step decreases. The two rules and define addition on numbers written with and a successor . Give each term the weight with , , : the first rule removes at least , the second , and weights are positive, so every chain is finite. Two rules can only conflict where one’s left side overlaps another’s; here none does, so the system is locally confluent, and confluent by Newman’s lemma: every closed sum has exactly one value. Without termination the lemma fails: exercise 5.10 gives four elements that show it.
5.3 Data as functions
The -calculus has no numbers, no booleans and no pairs, and needs none: each can be represented by what it does.
Definition 5.11 (Church boolean, Church numeral)
The Church booleans are and : a boolean chooses between two arguments. The Church numeral of is , with applications of : the number is the operation “do something times”.
A conditional needs no keyword: is when is and when it is . A pair holds its two components until a selector is given to it: , with . Arithmetic follows from “ times”: does once more than does; does times after times; does “ times”, times; and applies “multiply by ” times, starting from the function itself.
pub fn defs() -> Vec<(&'static str, Term)> {
let src = [
("true", r"\a b. a"), ("false", r"\a b. b"),
("pair", r"\a b f. f a b"), ("fst", r"\p. p true"), ("snd", r"\p. p false"),
("zero", r"\f x. x"), ("succ", r"\n f x. f (n f x)"),
("plus", r"\m n f x. m f (n f x)"), ("mult", r"\m n f. m (n f)"),
("exp", r"\m n. n m"),
("pred", r"\n. fst (n (\p. pair (snd p) (succ (snd p))) (pair zero zero))"),
];
let mut out: Vec<(&str, Term)> = vec![];
for (name, s) in src {
let t = term::parse_with(s, &out).expect("a definition");
out.push((name, t));
}
out
}
parse_with replaces a name by its term. code/bachelor-3/05-lambda-calculus/listings/encode.rsThe predecessor is the hard one, because a numeral can only do something times, never undo a step. The trick is to count pairs: start from and apply times the step . After steps the pair is for , so after steps its first component is (and when ). The definition pred in Listing 5.4 is exactly that.
$ rustc --edition 2021 -O -o church church.rs && ./church
term normal applicative normal form
succ c2 3 3 \f. \x. f (f (f x)) (the numeral 3)
plus c2 c3 6 6 \f. \x. f (f (f (f (f x)))) (the numeral 5)
mult c2 c3 7 7 \f. \x. f (f (f (f (f (f x))))) (the numeral 6)
exp c2 c3 16 10 \x. \x'. x (x (x (x (x (x (x (x x'))))))) (the numeral 8)
pred c3 36 43 \f. \x. f (f x) (the numeral 2)
fst (pair c1 c2) 6 6 \f. \x. f x (the numeral 1)
exp c2 c3 prints its numeral with the names x and x', an -variant of .Addition and multiplication take a handful of steps, the same under both strategies; exponentiation already differs, 16 steps against 10, and the predecessor takes dozens, 36 against 43. The weekend problem measures how the counts grow with the numbers.
5.4 Recursion without names
The -calculus has no way to name a function, so a function cannot call itself by name. It can, however, receive itself as an argument. Write the factorial as a functional that takes “the function to call recursively” as a parameter:
The factorial is the function with : a fixed point of .
Definition 5.12 (Fixed-point combinator)
A fixed-point combinator is a closed term such that for every term , where is the equivalence generated by -reduction.
The best known is
Indeed , and the argument of is the term reduced to in one step. Under call by value, is useless: the argument is evaluated before is ever entered, and it unfolds again, without end. Wrapping it in a delays it:
is a fixed-point combinator for call by value, since is already a value. Listing 5.5 runs both, in the small language of the next section, which has integers and if.
const Y: &str = r"\f. (\x. f (x x)) (\x. f (x x))";
const Z: &str = r"\f. (\x. f (\v. x x v)) (\x. f (\v. x x v))";
const F: &str = r"\fact. \n. if n == 0 then 1 else n * fact (n - 1)";
fn size(e: &lam::E) -> usize {
lam::show(e).len() // a crude but monotone measure: printed length
}
fn main() {
let programs = [
("Z F 5", format!("({Z}) ({F}) 5")),
("letrec", format!("letrec fact = {} in fact 5", &F[7..])),
("Y F 5", format!("({Y}) ({F}) 5")),
];
for (name, src) in programs {
let e = lam::parse(&src).expect("a program");
let mut last = 0;
let (r, steps) = smallstep::run(&e, 2_000, &mut |_, t| last = size(t));
match r {
Ok(v) => println!("{name:<7} value {} after {steps} steps", lam::show(&v)),
Err(m) => println!("{name:<7} {m}; the term is now {last} characters long"),
}
}
}
letrec, and through , all under call by value. code/bachelor-3/05-lambda-calculus/listings/ycomb.rs$ rustc --edition 2021 -O -o ycomb ycomb.rs && ./ycomb
Z F 5 value 120 after 46 steps
letrec value 120 after 35 steps
Y F 5 no value after 2000 steps; the term is now 108021 characters long
letrec in 35; never reaches a value, and the term it rewrites keeps growing.A language does not need in its programs: letrec f = \x. e1 in e2 is sugar for binding to the fixed point of , and the semantics of the next section gives it directly, by one rule that unfolds the definition once. It saves the eleven steps spends rebuilding itself.
5.5 Small steps and big steps
The -language of this chapter and the next, .lam files, adds to the -calculus the integers, the booleans, let, letrec, if, pairs and five operators. Its syntax tree is in Listing 5.6; the optional type on a is for chapter 6.
pub enum E {
Int(i64),
Bool(bool),
Var(String),
Lam(String, Option<Ty>, Box<E>),
App(Box<E>, Box<E>),
Let(String, Box<E>, Box<E>),
LetRec(String, Box<E>, Box<E>), // letrec f = \x. e1 in e2
Op(Op, Box<E>, Box<E>),
If(Box<E>, Box<E>, Box<E>),
Pair(Box<E>, Box<E>),
Fst(Box<E>),
Snd(Box<E>),
}
Definition 5.13 (Operational semantics, small-step, big-step)
An operational semantics defines the meaning of a program by rules describing how it runs. A small-step semantics defines a relation , one step of computation, and a program’s result is the value with . A big-step semantics defines a relation , “ evaluates to ”, directly, by rules whose premises evaluate the parts of .
The values are the integers, the booleans, the abstractions, and the pairs of values. The program is closed, and call by value only ever substitutes values, which are then closed too: nothing can be captured, and substitution by name is safe. These are the small-step rules for application, let, letrec and if; an operator applied to two values computes (), and its operands are reduced left to right like an application’s.
The rules without premises compute; those with a premise only say where to look. The interpreter of Listing 5.7 is read off them, one match arm per rule, in the same order; a term no rule applies to is stuck, and the interpreter says why.
pub fn step(e: &E) -> Result<E, String> {
let st = |e: &E| step(e).map(b);
Ok(match e {
E::App(f, a) if !is_value(f) => E::App(st(f)?, a.clone()),
E::App(f, a) if !is_value(a) => E::App(f.clone(), st(a)?),
E::App(f, v) => match &**f {
E::Lam(x, _, body) => subst(body, x, v), // beta for values
_ => return Err(format!("{} is not a function", show(f))),
},
E::Let(x, a, body) if !is_value(a) => E::Let(x.clone(), st(a)?, body.clone()),
E::Let(x, v, body) => subst(body, x, v),
E::LetRec(f, lam, body) => subst(body, f, &unfold(f, lam)),
E::Op(op, a, c) if !is_value(a) => E::Op(*op, st(a)?, c.clone()),
E::Op(op, a, c) if !is_value(c) => E::Op(*op, a.clone(), st(c)?),
E::Op(op, a, c) => arith(*op, a, c)?,
E::If(c, t, f) if !is_value(c) => E::If(st(c)?, t.clone(), f.clone()),
E::If(c, t, f) => match **c {
E::Bool(true) => (**t).clone(),
E::Bool(false) => (**f).clone(),
_ => return Err(format!("the condition {} is not a boolean", show(c))),
},
E::Pair(a, c) if !is_value(a) => E::Pair(st(a)?, c.clone()),
E::Pair(a, c) => E::Pair(a.clone(), st(c)?),
E::Fst(p) | E::Snd(p) if !is_value(p) => {
let p2 = st(p)?;
if matches!(e, E::Fst(_)) { E::Fst(p2) } else { E::Snd(p2) }
}
E::Fst(p) | E::Snd(p) => match &**p {
E::Pair(a, c) => if matches!(e, E::Fst(_)) { (**a).clone() } else { (**c).clone() },
_ => return Err(format!("{} is not a pair", show(p))),
},
E::Var(x) => return Err(format!("'{x}' is not bound")),
E::Int(_) | E::Bool(_) | E::Lam(..) => return Err("a value makes no step".into()),
})
}
The big-step rules say the same thing at once, from the leaves of a derivation up:
Read as an algorithm, the big-step rules are a recursive evaluator, the shape of chapter 4’s interpreter: each recursive call builds one premise (Listing 5.8).
match e {
E::Int(_) | E::Bool(_) | E::Lam(..) => Ok(e.clone()), // a value evaluates to itself
E::Var(x) => Err(format!("'{x}' is not bound")),
E::App(f, a) => {
let f = ev(f, z)?;
let v = ev(a, z)?;
match f {
E::Lam(x, _, body) => ev(&subst(&body, &x, &v), z),
_ => Err(format!("{} is not a function", show(&f))),
}
}
E::Let(x, a, body) => {
let v = ev(a, z)?;
ev(&subst(body, x, &v), z)
}
E::LetRec(f, lam, body) => ev(&subst(body, f, &unfold(f, lam)), z),
E::Op(op, a, c) => {
let va = ev(a, z)?;
let vc = ev(c, z)?;
arith(*op, &va, &vc)
}
E::If(c, t, f) => match ev(c, z)? {
E::Bool(true) => ev(t, z),
E::Bool(false) => ev(f, z),
other => Err(format!("the condition {} is not a boolean", show(&other))),
},
E::Pair(a, c) => Ok(E::Pair(b(ev(a, z)?), b(ev(c, z)?))),
E::Fst(p) | E::Snd(p) => match ev(p, z)? {
E::Pair(a, c) => Ok(if matches!(e, E::Fst(_)) { *a } else { *c }),
other => Err(format!("{} is not a pair", show(&other))),
},
}
}
z counts the nodes, and those whose rule computes. code/bachelor-3/05-lambda-calculus/listings/bigstep.rsOutput 5.3 runs sum.lam, by recursion, both ways. The small-step trace shows what the big-step derivation hides: the pending additions pile up on the left, 3 + (2 + (1 + ...)), and are only performed once the recursion has bottomed out. The demonstration prints the unfolded function as <sum> and an unfolded letrec with its definition elided.
$ rustc --edition 2021 -O -o semantics_demo semantics_demo.rs && ./semantics_demo sum.lam
0 letrec sum = \n. if n == 0 then 0 else n + sum (n - 1) in sum 3
1 <sum> 3
2 letrec sum = ... in if 3 == 0 then 0 else 3 + sum (3 - 1)
3 if 3 == 0 then 0 else 3 + <sum> (3 - 1)
4 if false then 0 else 3 + <sum> (3 - 1)
5 3 + <sum> (3 - 1)
6 3 + <sum> 2
7 3 + (letrec sum = ... in if 2 == 0 then 0 else 2 + sum (2 - 1))
8 3 + (if 2 == 0 then 0 else 2 + <sum> (2 - 1))
9 3 + (if false then 0 else 2 + <sum> (2 - 1))
10 3 + (2 + <sum> (2 - 1))
11 3 + (2 + <sum> 1)
12 3 + (2 + (letrec sum = ... in if 1 == 0 then 0 else 1 + sum (1 - 1)))
13 3 + (2 + (if 1 == 0 then 0 else 1 + <sum> (1 - 1)))
14 3 + (2 + (if false then 0 else 1 + <sum> (1 - 1)))
15 3 + (2 + (1 + <sum> (1 - 1)))
16 3 + (2 + (1 + <sum> 0))
17 3 + (2 + (1 + (letrec sum = ... in if 0 == 0 then 0 else 0 + sum (0 - 1))))
18 3 + (2 + (1 + (if 0 == 0 then 0 else 0 + <sum> (0 - 1))))
19 3 + (2 + (1 + (if true then 0 else 0 + <sum> (0 - 1))))
20 3 + (2 + (1 + 0))
21 3 + (2 + 1)
22 3 + 3
23 6
small-step: 6 after 23 steps
big-step: 6 by a derivation of 46 nodes, 23 of them contractions, depth 18
sum.lam under the small-step rules, one line per step, then under the big-step rules: 23 steps, and a derivation with 23 computing nodes.The two counts are equal, and this is a theorem.
Theorem 5.14 (Small steps and big steps agree)
For a closed expression and a value : if and only if . Moreover, the number of steps equals the number of computing nodes of the derivation.
Proof. () By induction on the derivation. A value takes zero steps. For an application, the premises give, by induction, in steps, in and in . The congruence rules lift the first two reductions to the whole term (a short induction on their length): , then one computing step gives , and more give . In all steps, the node itself being the one computing step. The other rules are alike.
() First a lemma: if and by a derivation with computing nodes, then with . By induction on the step. If it is , build the application node from , and the given derivation. If it is with , the derivation of contains ; by induction with one more computing node; put it back in place. The other rules are alike. Then the theorem follows by induction on the number of steps of , starting from . ∎
The test small_and_big_step_agree checks the theorem on six programs. It says nothing of programs that do not terminate: a small-step run of is an infinite sequence, while has no derivation at all. Big-step semantics cannot tell a loop from a stuck program, both having no derivation; small-step semantics can, which is why proofs of type safety in the next chapter use it.
Remark 5.15
A third style, denotational semantics, gives each program a mathematical object as its meaning: a function from inputs to outputs, built compositionally from the meanings of the parts. A recursive definition then denotes a fixed point of a function on a suitable ordered set, and a loop denotes an “undefined” element. It answers questions operational semantics answers badly, such as when two programs are interchangeable in every context; it needs more mathematics than this chapter has room for.
In practice — Keep the rules runnable
Rules written on paper drift away from the compiler they describe. Rules read off as an interpreter, as here, can be run on the compiler’s test programs: a disagreement between the two is then a bug in one of them, and the rules, being short, are the easier to check. The compiler of chapter 7 is held to the interpreter of chapter 4 in this way.
History — Functions as the foundation
Alonzo Church introduced the -notation in 1932, in a system meant as a foundation of logic. In 1936 he and J. Barkley Rosser proved the confluence theorem that bears their names. Max Newman’s lemma appeared in 1942, in a paper on equivalence defined by combinatorial rules. Nicolaas de Bruijn’s nameless notation was published in 1972, as a tool for manipulating formulas by machine. The big-step style of semantics was named natural semantics by Gilles Kahn in 1987.
5.6 Exercises
Exercise 5.1 ★
Give the free variables of \x. x y, of (\x. x) x and of \x. \y. z (x y) w.
Solution
Solution of Exercise 5.1.
; (the last is outside the abstraction); (exercise_1_free_variables).
Exercise 5.2 ★
Which of these pairs are -equivalent? \x. \y. x y and \y. \x. y x; \x. \y. x y and \x. \y. y x; \x. x z and \z. z z. Give the de Bruijn form of each term.
Solution
Solution of Exercise 5.2.
The first pair is -equivalent: both are . The second is not: against . The third is not: in \x. x z the is free, giving , while \z. z z is ; renaming to would capture the free (exercise_2_alpha_equivalence).
Exercise 5.3 ★
Reduce (\x. \y. x y) y by one -step. What does a substitution that ignores capture give, and why is it wrong?
Solution
Solution of Exercise 5.3.
The test exercise_3_capture_avoided checks the answer. One step gives \y'. y y', since the bound is renamed before the free is substituted. A substitution that ignores capture gives \y. y y, a function that applies its argument to itself, where the term meant “apply the free to the argument”.
Exercise 5.4 ★
Predict the lines that church.rs would print for succ c4 and for plus c4 c0: both step counts and the numeral.
Solution
Solution of Exercise 5.4.
succ c4: 3 steps under each strategy, the numeral 5. plus c4 c0: 6 and 6, the numeral 4. The counts of and do not depend on the numbers (exercise_4_predict_church_lines).
Exercise 5.5 ★★
A first version of subst handled abstractions with Lam(x, b) => Lam(x.clone(), Box::new(subst(j + 1, s, b))). Find a term that normal order reduces wrongly with it, say what it gives, and fix the line.
Solution
Solution of Exercise 5.5.
Take \a. (\x. \y. x) a, whose normal form is \a. \y. a. Normal order reduces the redex under \a; its argument is index 0, shifted to 1 by beta before the substitution. Under \y the body’s is index 1, and the substituted term should now be index 2 (it crosses \y); the faulty line keeps it at 1, which after the redex’s disappears points at y. The result is \a. \y. y. The fix shifts the substituted term under each : Lam(x, b) => Lam(x.clone(), Box::new(subst(j + 1, &shift(1, 0, s), b))), as in Listing 5.2 (exercise_5_shifting_matters shows both results).
Exercise 5.6 ★★
With the definitions of Listing 5.4 and , which computes , write , which maps to and every other numeral to , and , which tests two numerals for equality. Test them on all numerals up to 5.
Solution
Solution of Exercise 5.6.
: zero applications leave , and one or more replace it by . With , : since subtraction stops at zero, both differences are zero exactly when . In exercises/ex6_church.rs; exercise_6_is_zero_and_eq checks all pairs up to 5.
Exercise 5.7 ★★
Prove that if two strategies both lead a term to a normal form, they lead it to the same one. Then reduce plus c2 c3 by call by name: where does it stop, and why does this not contradict what you just proved?
Solution
Solution of Exercise 5.7.
If by one strategy and by another, both normal forms, then both are reducts of , and Corollary 5.8 gives up to -equivalence: a strategy only chooses among -steps. Call by name stops after the two steps that substitute the numerals, at \f. \x. c2 f (c3 f x), with the numerals written out (exercise_7_call_by_name_stops_early). It does not reduce under a , so it stops at an abstraction that is not in normal form. There is no contradiction: the result was about strategies that reach a normal form, and this one has not; normal order, continuing from there, reaches .
Exercise 5.8 ★★
Count the -steps that normal order takes to reduce to normal form, as a function of and , and explain why does not appear.
Solution
Solution of Exercise 5.8.
(exercise_8_mult_steps, for ). Two steps substitute and , giving . One step unfolds : , with copies of . Normal order then takes the outermost copy: in one step, and applying it to its argument is a second; and so on for each of the copies. The number does not appear because one -step substitutes into all occurrences of the numeral’s body at once: the step count ignores the size of what a step copies.
Exercise 5.9 ★★
Using only the small-step rules of if and their congruence rule, show that holds exactly when and , or and . Deduce the big-step rules of if.
Solution
Solution of Exercise 5.9.
Write . If is not a value, the only rule that applies to is the congruence rule, which steps and keeps the shape. So a reduction begins with steps of , as long as is not a value; it must reach a value , since otherwise keeps its shape and never becomes the value . If is neither nor , is stuck. If it is , the next step gives , and the rest is ; likewise for and . Conversely, the congruence rule lifts to , one step gives , and . By Theorem 5.14, to a value is , which gives the two big-step rules: and give ; and give .
Exercise 5.10 ★★★
On the set , let , , and . Show that this system is locally confluent but not confluent, and say which hypothesis of Newman’s lemma fails. Then prove that the measure used for the rules of in this chapter decreases when a rule is applied inside a larger term, not only at the top.
Solution
Solution of Exercise 5.10.
Local confluence: from , the reducts and meet at , since ; from , the reducts and meet at , since . The other elements have at most one reduct. Not confluent: and , and and are distinct normal forms. Termination fails: . In context: is strictly increasing in each argument (, ), so if , then for every context , by induction on the depth of the hole in . A rule applied anywhere therefore decreases the weight of the whole term.
Exercise 5.11 ★★★
Prove that has no normal form. Show that , with and , has one, that normal order reaches it in two steps, and that call by value never does.
Solution
Solution of Exercise 5.11.
has exactly one redex, itself (its two parts are abstractions in normal form), and contracting it gives again. So every reduction from is , and every term on it contains a redex: no normal form. Normal order: , two steps, and is a normal form. Call by value: , a value, but then the argument must be reduced to a value before the redex may be contracted, and it never becomes one (exercise_11_omega). By Corollary 5.8, is the only normal form of ; call by value simply never reaches it.
Exercise 5.12 ★★★
The Krivine machine evaluates by call by name without substitution. Its state is a term, an environment (a list of closures, one per enclosing ) and a stack of closures (pending arguments), where a closure is a term with its environment. An application pushes its argument, as a closure, and continues with the function; an abstraction pops a closure into its environment and continues with its body; a variable continues with the -th closure of the environment. Implement it on de Bruijn terms, with a function that reads a closure back as a term, and test that it reaches the same term as call by name, in the same number of -steps.
Solution
Solution of Exercise 5.12.
exercises/ex12_krivine.rs. The environment is shared through reference counting, so pushing an argument costs one closure, not a copy of the term. When the machine stops (an abstraction with an empty stack, or a free variable), the result is read back: each free index of the term is replaced by its closure, read back in turn and shifted by the number of ’s crossed; the pending arguments are applied to it. exercise_12_krivine_matches_call_by_name runs eight terms, Church arithmetic and among them: the read-back term is -equivalent to the result of call by name, and the number of pops equals the number of -steps, since each pop is exactly the contraction call by name makes at that point, with the substitution postponed into the environment.
5.7 Weekend problem
Problem 5.1
Weekend problem — Arithmetic with nothing but functions
Church numerals are a complete arithmetic: every computable function on numbers can be written with them. This problem measures what it costs, counting -steps to normal form, under normal order (the strategy that always finds a normal form) and applicative order. The program pb_counts.rs prints the counts it needs.
$ rustc --edition 2021 -O -o pb_counts pb_counts.rs && ./pb_counts
n mult n 3 exp 2 n pred n sub 10 n
nor app nor app nor app nor app
0 3 3 - - 9 14 4 12
1 5 5 4 4 16 23 110 110
2 7 7 8 7 26 34 206 199
3 9 9 16 10 36 43 292 279
4 11 11 32 13 46 52 368 350
5 13 13 64 16 56 61 434 412
6 15 15 - - 66 70 490 465
7 17 17 - - 76 79 536 509
8 19 19 - - 86 88 572 544
9 21 21 - - 96 97 598 570
10 23 23 - - 106 106 614 585
nor) and applicative order (app); exp c2 c0 is left out, its normal form \x. x not being a numeral.Part I — Numerals and addition.
- Write , and reduce to normal form by hand, counting the steps.
- Reduce by normal order. Why do the counts of Output 5.1 for not depend on the numbers?
- Is the number of -steps a fair measure of the work? What does each step of copy, and how large is the result?
- How many symbols does have? Compare with the binary representation of .
- Show that also computes .
- Why does that second addition need more steps than as grows?
Part II — Multiplication and exponentiation.
- From Output 5.4, give the counts for as a formula, and check it on two lines.
- Give the counts for under both strategies as formulas.
- Explain the doubling under normal order: what does normal order copy that applicative order has already reduced?
- Is normal order always slower? Give a term for which it takes fewer steps than applicative order.
- What size does the normal form of have? Does its step count, under either strategy, measure the work of writing it out?
- Which strategy would you choose for a calculator built on Church numerals, and what would call by need change?
Part III — The predecessor.
- Show that after applications of the step to , the pair is .
- Why does give ?
- From Output 5.4, give the normal-order count of for as a formula.
- How many steps does each round of the step take under normal order? Where do the remaining ones go?
- Give the applicative-order count for as a formula. Which strategy wins for large ?
- Compare with the cost of a predecessor on binary numbers. What has the encoding cost?
Part IV — Subtraction.
- Show that reduces to .
- From the column
sub 10 n, compute the differences between consecutive normal-order counts. What do you notice? - Suppose the -th predecessor, for , costs as much as applied to the numeral , plus 4 steps in all to unfold . Derive a formula for the count when , and check it against the table.
- Under normal order, the predecessors are applied to terms that are not yet numerals. Why does the assumption of the previous question still hold?
- What is the order of growth of the count in and ? At ?
- Sum up: give the cost of and of under normal order, and say what a machine integer would cost instead.
Solution
Solution of Problem 5.1.
The formulas are asserted in tests/pb_test.rs.
1. . Then, in 3 steps,
2. Two steps substitute the numerals: . Then unfolds and is applied (2 steps), giving , and likewise (2 steps): 6 in all. Each numeral is unfolded in two steps whatever its value, because a step substitutes into all the occurrences at once.
3. No. A step substitutes a term, which may be large, and copies it once per occurrence of the variable. The steps of substitute and into bodies of sizes about and , and the result has size : the work is at least linear, the step count constant.
4. Two ’s and applications of , so symbols, against bits in binary: numerals are unary.
5. with applications, which is by induction on , since .
6. It applies times, at 3 steps each, so it takes steps whatever is, against a constant 6 for , which moves all of ’s applications of in one substitution.
7. under both strategies: 3, 5, 7, 9, …; for instance gives 11 and gives 23.
8. Normal order: (4, 8, 16, 32, 64). Applicative order: (4, 7, 10, 13, 16).
9. becomes , which unfolds to . Normal order reduces the outermost first; uses its argument twice, so the inner, unreduced tower is copied twice and each copy is reduced separately: the work doubles at each level. Applicative order reduces the innermost first, to a normal form, so each level costs 3 steps on an argument already in normal form.
10. No. On normal order takes 2 steps and applicative order never stops; on normal order takes one step and applicative order first reduces , at any cost.
11. The normal form is , of size . The applicative steps cannot write it out in constant work each: later steps substitute ever larger terms. Step counts measure neither strategy’s real work here; the size of the result is a lower bound for both.
12. Applicative order: Church arithmetic uses its arguments several times, and reducing them once, before they are copied, avoids the doubling. Call by need would share each argument’s reduction among its copies, keeping normal order’s guarantee of finding a normal form while removing the duplicated work.
13. By induction on : one step takes to ; if the pair is , the step gives .
14. applies the step zero times, leaving , whose first component is .
15. : 16, 26, 36, …, 106 ( takes 9).
16. 10 steps per round of the step: building the new pair and computing of the second component. The remaining 6 are a constant: unfolding , applying the numeral to the step and the initial pair, and selecting the first component at the end.
17. for (34, 43, …, 106; 23 for , 14 for ). Normal order is cheaper up to , the two meet at (106), and applicative order wins beyond, by one step per round.
18. On binary numbers a predecessor changes the trailing zeros and the last one: bit operations at worst, a constant on average, and one instruction on a machine word. The unary encoding costs a factor of .
19. , and by induction on , using and , this is .
20. 106, 96, 86, 76, 66, 56, 46, 36, 26, 16: they decrease by 10, and each is the cost of on .
21. . For : gives , gives 614, as in the table (the test checks all ).
22. uses its argument once. Normal order duplicates only arguments that are used several times, so each inner predecessor is reduced exactly once, when the outer one needs it as a numeral; the contractions are the same as if it had been reduced first, in another order.
23. for ; at , .
24. Under normal order, takes -steps, , and takes , . A machine integer subtracts in one instruction: the -calculus can compute everything, at a price that only matters once one counts.