---
title: "The Lambda Calculus and Operational Semantics"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 5
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 5 — The 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 $\forall x.\,\varphi$, the quantifier binds the occurrences of $x$ in $\varphi$; the others are free (Year 2 volume, predicate logic).

**Definition 5.1 (λ\lambdaλ-term).**

The *$\lambda$-terms* over a set of variables are given by the grammar $M ::= x \mid \lambda x.\,M \mid M\,M$. A term $\lambda x.\,M$ is an *abstraction*: the function that maps $x$ to $M$. A term $M\,N$ is an *application*: the function $M$ called with the argument $N$.

[Application](#def-b3-lambda-calculus-terms) associates to the left, so $f\,a\,b$ is $(f\,a)\,b$, a function of two arguments taken one at a time; and the body of a $\lambda$ extends as far right as possible, so $\lambda x.\,\lambda y.\,x\,y$ is $\lambda x.\,(\lambda y.\,(x\,y))$. In code we write `\x. M` for $\lambda x.\,M$, and `\x y. M` for $\lambda x.\,\lambda y.\,M$. A $\lambda$ binds its variable in its body exactly as a quantifier does in logic: in $\lambda x.\,x\,y$ the occurrence of $x$ is bound and $y$ is free, and the free variables of a term are defined by the same structural recursion as for formulas.

**Definition 5.2 (α\alphaα-equivalence, capture-avoiding substitution).**

Two terms are *$\alpha$-equivalent* if they differ only in the names of bound variables, renamed consistently: $\lambda x.\,x\,y$ and $\lambda z.\,z\,y$ are, $\lambda x.\,x\,y$ and $\lambda y.\,y\,y$ are not. The *capture-avoiding substitution* $M[x := N]$ replaces the free occurrences of $x$ in $M$ by $N$, after renaming the bound variables of $M$ that would otherwise capture a free variable of $N$.

Capture is the whole difficulty. Substituting $y$ for $x$ in $\lambda y.\,x$ naively gives $\lambda y.\,y$, the identity, where we wanted the function that ignores its argument and returns $y$. The correct result renames first: $\lambda y'.\,y$. Terms are considered up to $\alpha$-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](#def-b3-lambda-calculus-debruijn) removed the names altogether.

**Definition 5.3 (de Bruijn index).**

In the *de Bruijn* notation, a bound variable is replaced by the number of $\lambda$’s between its occurrence and its binder: 0 for the nearest enclosing $\lambda$, 1 for the next one out, and so on. The term $\lambda x.\,\lambda y.\,x\,y$ becomes $\lambda.\,\lambda.\,1\;0$.

Two $\alpha$-equivalent terms have the same [de Bruijn](#def-b3-lambda-calculus-debruijn) form, so $\alpha$-equivalence becomes plain equality of trees. [Listing 5.1](#lst-b3-lambda-calculus-term) 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.

```rust
#[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,
    }
}
```

***Listing 5.1.** $\lambda$-terms with [de Bruijn](#def-b3-lambda-calculus-debruijn) indices; $\alpha$-equivalence is structural equality, with the names ignored. code/bachelor-3/05-lambda-calculus/listings/term.rs*

![A term as a tree, each variable joined to its binder (dashed). The index counts the nodes crossed on the way up: from y the path meets z first, so y is 1, and so is x, which meets y.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lambda-calculus/fig-c976c07d0030.svg)

*A term as a tree, each variable joined to its binder (dashed). The index counts the $\lambda$ nodes crossed on the way up: from $y$ the path meets $\lambda z$ first, so $y$ is 1, and so is $x$, which meets $\lambda y$.*

Substitution must now keep indices right. When a term $N$ is substituted under a $\lambda$, its free indices must grow by one, since they now cross one more binder: this is the *shift*. And when a $\lambda$ disappears in a reduction, the indices that pointed past it must shrink by one. [Listing 5.2](#lst-b3-lambda-calculus-subst) does both.

```rust
/// 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))
}
```

***Listing 5.2.** Shifting and substitution on [de Bruijn](#def-b3-lambda-calculus-debruijn) terms. No name is ever compared, so no capture can happen. code/bachelor-3/05-lambda-calculus/listings/reduce.rs*

## 5.2 Reduction

**Definition 5.4 (β\betaβ-reduction, redex, normal form).**

A *redex* is a subterm of the form $(\lambda x.\,M)\,N$. *$\beta$-reduction* replaces one redex by $M[x := N]$, anywhere in a term; we write $M \to_\beta M'$ for one step and $\to_\beta^*$ for zero or more. A term with no redex is in *normal form*.

The term $(\lambda x.\,\lambda y.\,x\,y)\,y$ reduces in one step to $\lambda y'.\,y\,y'$, renaming to avoid capture. Some terms have no [normal form](#def-b3-lambda-calculus-beta): $\Omega = (\lambda x.\,x\,x)\,(\lambda x.\,x\,x)$ reduces to itself, forever. And a term with several [redexes](#def-b3-lambda-calculus-beta) 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](#def-b3-lambda-calculus-beta) to reduce next. *Normal-order reduction* reduces the leftmost outermost [redex](#def-b3-lambda-calculus-beta), also under a $\lambda$. *Call by name* does the same but never reduces under a $\lambda$ or inside an argument. *Call by value* reduces a [redex](#def-b3-lambda-calculus-beta) $(\lambda x.\,M)\,N$ only once $N$ is a value (here, an [abstraction](#def-b3-lambda-calculus-terms)), and never under a $\lambda$. *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](#lst-b3-lambda-calculus-step) implements four strategies: the three above and *applicative order*, leftmost innermost, which reduces arguments first and also goes under $\lambda$’s; it is [call by value](#def-b3-lambda-calculus-strategy) continued to a [normal form](#def-b3-lambda-calculus-beta). Each step returns the new term, or nothing when the strategy finds no [redex](#def-b3-lambda-calculus-beta).

```rust
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)
                }
            }
        }
    }
}
```

***Listing 5.3.** One step of each strategy. Normal order and [call by name](#def-b3-lambda-calculus-strategy) contract a [redex](#def-b3-lambda-calculus-beta) at the top before looking inside; [call by value](#def-b3-lambda-calculus-strategy) and applicative order look inside first. code/bachelor-3/05-lambda-calculus/listings/reduce.rs*

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](#def-b3-lambda-calculus-strategy) even stops early, at a term whose head is the free variable $a$, since it never reduces inside an argument.

![All the reducts of one term, an arrow per -step (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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lambda-calculus/fig-22a4013e7993.svg)

*All the reducts of one term, an arrow per $\beta$-step (`reduction_graph_of_the_figure` enumerates them: six terms, seven arrows). Normal order copies the unreduced argument and reduces it twice; [call by value](#def-b3-lambda-calculus-strategy) reduces it once, before the copy.*

Every path that ends, ends at $a\,a$. 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 $A$ with a relation $\to$ on it, often given by rules that rewrite terms (a *term rewriting system*); $\to^*$ is its reflexive transitive closure. The system is *confluent* if whenever $a \to^* b$ and $a \to^* c$, there is a $d$ with $b \to^* d$ and $c \to^* d$; *locally confluent* if this holds whenever $a \to b$ and $a \to c$ in one step each; *terminating* if there is no infinite chain $a_0 \to a_1 \to \cdots$.

**Theorem 5.7 (Church–Rosser).**

$\beta$-reduction is [confluent](#def-b3-lambda-calculus-rewriting).

**Proof.** *Admitted at this level.* ∎

Local [confluence](#def-b3-lambda-calculus-rewriting) is not enough here, since $\beta$-reduction does not terminate, and a one-step diamond fails: reducing a [redex](#def-b3-lambda-calculus-beta) 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](#def-b3-lambda-calculus-beta) at once, shows by induction on terms that it satisfies the one-step diamond, and notes that its reflexive transitive closure is $\to_\beta^*$.

**Corollary 5.8.**

A $\lambda$-term has at most one [normal form](#def-b3-lambda-calculus-beta), up to $\alpha$-equivalence.

**Proof.** If $M \to_\beta^* N_1$ and $M \to_\beta^* N_2$ with both in [normal form](#def-b3-lambda-calculus-beta), [confluence](#def-b3-lambda-calculus-rewriting) gives $P$ with $N_1 \to_\beta^* P$ and $N_2 \to_\beta^* P$. A [normal form](#def-b3-lambda-calculus-beta) reduces only to itself, so $N_1 = P = N_2$. ∎

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 $\lambda$-term has a [normal form](#def-b3-lambda-calculus-beta), [normal-order reduction](#def-b3-lambda-calculus-strategy) reaches it.

**Proof.** *Admitted at this level.* ∎

The proof goes through the *standardisation theorem*: any reduction to a [normal form](#def-b3-lambda-calculus-beta) can be reordered so that it contracts [redexes](#def-b3-lambda-calculus-beta) 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 $(\lambda x.\,\lambda y.\,y)\,\Omega$ it reduces $\Omega$ forever, while normal order discards it in one step (exercise [5.11](#exo-b3-lambda-calculus-11)).

For a terminating system, local [confluence](#def-b3-lambda-calculus-rewriting) 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](#def-b3-lambda-calculus-rewriting) [rewriting system](#def-b3-lambda-calculus-rewriting) is [confluent](#def-b3-lambda-calculus-rewriting).

**Proof.** Since the system terminates, the relation “$b$ is reachable from $a$ 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 $a$ in one or more steps, and prove it for $a$. The property is: every two reducts of $a$ have a common reduct.

Let $a \to^* b$ and $a \to^* c$. If either reduction is empty, say $a = b$, take $d = c$. Otherwise write $a \to b_1 \to^* b$ and $a \to c_1 \to^* c$. By local [confluence](#def-b3-lambda-calculus-rewriting), there is $e$ with $b_1 \to^* e$ and $c_1 \to^* e$. Now $b_1$ is a reduct of $a$, so the induction hypothesis applies to it: $b$ and $e$, both reducts of $b_1$, have a common reduct $f$. Likewise $c_1$ is a reduct of $a$, and $f$ and $c$ are both reducts of $c_1$ (since $c_1 \to^* e \to^* f$), so they have a common reduct $d$. Then $b \to^* f \to^* d$ and $c \to^* d$. ∎

![Left: what confluence asks. Right: the proof of Newman’s lemma, three tiles. Local confluence closes the top diamond; the induction hypothesis, used at the two one-step reducts b_1 and c_1, closes the two others. Termination is what makes the induction legitimate.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lambda-calculus/fig-be4f4d96a69f.svg)

*Left: what [confluence](#def-b3-lambda-calculus-rewriting) asks. Right: the proof of Newman’s lemma, three tiles. Local [confluence](#def-b3-lambda-calculus-rewriting) closes the top diamond; the induction hypothesis, used at the two one-step reducts $b_1$ and $c_1$, closes the two others. Termination is what makes the induction legitimate.*

Termination is usually proved by a *measure*: a function to the natural numbers that every step decreases. The two rules $\mathit{add}(0, y) \to y$ and $\mathit{add}(s(x), y) \to s(\mathit{add}(x, y))$ define addition on numbers written with $0$ and a successor $s$. Give each term the weight $w$ with $w(0) = 1$, $w(s(t)) = w(t) + 1$, $w(\mathit{add}(t, u)) = 2w(t) + w(u)$: the first rule removes at least $w(y) + 2 - w(y) = 2$, the second $2(w(x)+1) + w(y) - 2w(x) - w(y) - 1 = 1$, 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](#def-b3-lambda-calculus-rewriting), and [confluent](#def-b3-lambda-calculus-rewriting) by Newman’s lemma: every closed sum has exactly one value. Without termination the lemma fails: exercise [5.10](#exo-b3-lambda-calculus-10) gives four elements that show it.

## 5.3 Data as functions

The $\lambda$-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 $\mathit{true} = \lambda a.\,\lambda b.\,a$ and $\mathit{false} = \lambda a.\,\lambda b.\,b$: a boolean chooses between two arguments. The *Church numeral* of $n$ is $c_n = \lambda f.\,\lambda x.\,f\,(f\,(\cdots(f\,x)))$, with $n$ [applications](#def-b3-lambda-calculus-terms) of $f$: the number $n$ is the operation “do something $n$ times”.

A conditional needs no keyword: $b\,M\,N$ is $M$ when $b$ is $\mathit{true}$ and $N$ when it is $\mathit{false}$. A pair holds its two components until a selector is given to it: $\mathit{pair} = \lambda a.\,\lambda b.\,\lambda f.\,f\,a\,b$, with $\mathit{fst}\,p = p\,\mathit{true}$. Arithmetic follows from “$n$ times”: $\mathit{succ}\,n$ does $f$ once more than $n$ does; $\mathit{plus}\,m\,n$ does $f$ $m$ times after $n$ times; $\mathit{mult}\,m\,n$ does “$f$ $n$ times”, $m$ times; and $\mathit{exp}\,m\,n = n\,m$ applies “multiply by $m$” $n$ times, starting from the function itself.

```rust
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
}
```

***Listing 5.4.** Booleans, pairs and arithmetic as $\lambda$-terms. Each name may use the earlier ones; `parse_with` replaces a name by its term. code/bachelor-3/05-lambda-calculus/listings/encode.rs*

The predecessor is the hard one, because a numeral can only do something $n$ times, never undo a step. The trick is to count pairs: start from $(0, 0)$ and apply $n$ times the step $(a, b) \mapsto (b, b + 1)$. After $k$ steps the pair is $(k - 1, k)$ for $k \ge 1$, so after $n$ steps its first component is $n - 1$ (and $0$ when $n = 0$). The definition `pred` in [Listing 5.4](#lst-b3-lambda-calculus-encode) 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)
```

***Output 5.1.** Six computations, each reduced to [normal form](#def-b3-lambda-calculus-beta) under normal order and under applicative order, with the number of $\beta$-steps. The [normal forms](#def-b3-lambda-calculus-beta) are recognised as numerals; `exp c2 c3` prints its numeral with the names `x` and `x'`, an $\alpha$-variant of $c_8$.*

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 $\lambda$-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:

$$
F = \lambda \mathit{fact}.\,\lambda n.\,\mathtt{if}\ n = 0\ \mathtt{then}\ 1\ \mathtt{else}\ n \times \mathit{fact}\,(n - 1).
$$

The factorial is the function $g$ with $F\,g = g$: a fixed point of $F$.

**Definition 5.12 (Fixed-point combinator).**

A *fixed-point combinator* is a closed term $\Theta$ such that $\Theta\,F =_\beta F\,(\Theta\,F)$ for every term $F$, where $=_\beta$ is the equivalence generated by $\beta$-reduction.

The best known is

$$
Y = \lambda f.\,(\lambda x.\,f\,(x\,x))\,(\lambda x.\,f\,(x\,x)).
$$

Indeed $Y\,F \to_\beta (\lambda x.\,F\,(x\,x))\,(\lambda x.\,F\,(x\,x)) \to_\beta F\,((\lambda x.\,F\,(x\,x))\,(\lambda x.\,F\,(x\,x)))$, and the argument of $F$ is the term $Y\,F$ reduced to in one step. Under [call by value](#def-b3-lambda-calculus-strategy), $Y$ is useless: the argument $x\,x$ is evaluated before $F$ is ever entered, and it unfolds again, without end. Wrapping it in a $\lambda$ delays it:

$$
Z = \lambda f.\,(\lambda x.\,f\,(\lambda v.\,x\,x\,v))\,(\lambda x.\,f\,(\lambda v.\,x\,x\,v))
$$

is a [fixed-point combinator](#def-b3-lambda-calculus-fixpoint) for [call by value](#def-b3-lambda-calculus-strategy), since $\lambda v.\,x\,x\,v$ is already a value. [Listing 5.5](#lst-b3-lambda-calculus-ycomb) runs both, in the small language of the next section, which has integers and `if`.

```rust
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"),
        }
    }
}
```

***Listing 5.5.** The factorial of 5 three ways: through $Z$, through `letrec`, and through $Y$, all under [call by value](#def-b3-lambda-calculus-strategy). 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
```

***Output 5.2.** $Z$ computes 120 in 46 steps, `letrec` in 35; $Y$ never reaches a value, and the term it rewrites keeps growing.*

A language does not need $Z$ in its programs: `letrec f = \x. e1 in e2` is sugar for binding $f$ to the fixed point of $\lambda f.\,\lambda x.\,e_1$, and the semantics of the next section gives it directly, by one rule that unfolds the definition once. It saves the eleven steps $Z$ spends rebuilding itself.

## 5.5 Small steps and big steps

The $\lambda$-language of this chapter and the next, `.lam` files, adds to the $\lambda$-calculus the integers, the booleans, `let`, `letrec`, `if`, pairs and five operators. Its syntax tree is in [Listing 5.6](#lst-b3-lambda-calculus-lam); the optional type on a $\lambda$ is for chapter [6](https://one-course.com/books/computer-science/5/en/chapter/6-type-systems-and-type-inference#ch-b3-type-systems).

```rust
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>),
}
```

***Listing 5.6.** The expressions of the $\lambda$-language. code/bachelor-3/05-lambda-calculus/listings/lam.rs*

**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 $e \to e'$, one step of computation, and a program’s result is the value $v$ with $e \to^* v$. A *big-step semantics* defines a relation $e \Downarrow v$, “$e$ evaluates to $v$”, directly, by rules whose premises evaluate the parts of $e$.

The values are the integers, the booleans, the [abstractions](#def-b3-lambda-calculus-terms), and the pairs of values. The program is closed, and [call by value](#def-b3-lambda-calculus-strategy) 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](#def-b3-lambda-calculus-terms), `let`, `letrec` and `if`; an operator applied to two values computes ($2 + 3 \to 5$), and its operands are reduced left to right like an [application](#def-b3-lambda-calculus-terms)’s.

$$
\begin{gather*}{\dfrac{\ }{(\lambda x.\,e)\,v \to e[x := v]}}

{\dfrac{e_1 \to e_1'}{e_1\,e_2 \to e_1'\,e_2}}

{\dfrac{e_2 \to e_2'}{v\,e_2 \to v\,e_2'}}

{\dfrac{\ }{\mathtt{let}\ x = v\ \mathtt{in}\ e \to e[x := v]}}

{\dfrac{\ }{\mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_2 \to e_2[f := \lambda x.\,\mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_1]}}

{\dfrac{\ }{\mathtt{if}\ \mathtt{true}\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to e_2}}

{\dfrac{e_1 \to e_1'}{\mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to \mathtt{if}\ e_1'\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3}}\end{gather*}
$$

The rules without premises *compute*; those with a premise only say where to look. The interpreter of [Listing 5.7](#lst-b3-lambda-calculus-small) 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.

```rust
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()),
    })
}
```

***Listing 5.7.** The small-step rules of the $\lambda$-language as a function: one arm per rule. code/bachelor-3/05-lambda-calculus/listings/smallstep.rs*

The big-step rules say the same thing at once, from the leaves of a derivation up:

$$
\begin{gather*}{\dfrac{\ }{v \Downarrow v}}

{\dfrac{e_1 \Downarrow \lambda x.\,e \qquad  e_2 \Downarrow v_2 \qquad  e[x := v_2] \Downarrow v}{e_1\,e_2 \Downarrow v}}

{\dfrac{e_1 \Downarrow v_1 \qquad  e_2[x := v_1] \Downarrow v}{\mathtt{let}\ x = e_1\ \mathtt{in}\ e_2 \Downarrow v}}

{\dfrac{e_1 \Downarrow \mathtt{true} \qquad  e_2 \Downarrow v}{\mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \Downarrow v}}

{\dfrac{e_1 \Downarrow n_1 \qquad  e_2 \Downarrow n_2}{e_1 + e_2 \Downarrow n_1 + n_2}}\end{gather*}
$$

Read as an algorithm, the big-step rules are a recursive evaluator, the shape of chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis)’s interpreter: each recursive call builds one premise ([Listing 5.8](#lst-b3-lambda-calculus-big)).

```rust
    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))),
        },
    }
}
```

***Listing 5.8.** The big-step rules as an evaluator. Each call is one node of the derivation; `z` counts the nodes, and those whose rule computes. code/bachelor-3/05-lambda-calculus/listings/bigstep.rs*

*The derivation of $(\lambda x.\,x + 1)\,2 \Downarrow 3$: six nodes, two of which compute (the [application](#def-b3-lambda-calculus-terms) and the addition). The small-step run takes exactly two steps: $(\lambda x.\,x + 1)\,2 \to 2 + 1 \to 3$.*

[Output 5.3](#out-b3-lambda-calculus-sum) runs `sum.lam`, $3 + 2 + 1 + 0$ 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
```

***Output 5.3.** `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 $e$ and a value $v$: $e \to^* v$ if and only if $e \Downarrow v$. Moreover, the number of steps equals the number of computing nodes of the derivation.

**Proof.** ($\Leftarrow$) By induction on the derivation. A value takes zero steps. For an [application](#def-b3-lambda-calculus-terms), the premises give, by induction, $e_1 \to^* \lambda x.\,e$ in $k_1$ steps, $e_2 \to^* v_2$ in $k_2$ and $e[x := v_2] \to^* v$ in $k_3$. The congruence rules lift the first two reductions to the whole term (a short induction on their length): $e_1\,e_2 \to^* (\lambda x.\,e)\,e_2 \to^* (\lambda x.\,e)\,v_2$, then one computing step gives $e[x := v_2]$, and $k_3$ more give $v$. In all $k_1 + k_2 + 1 + k_3$ steps, the node itself being the one computing step. The other rules are alike.

($\Rightarrow$) First a lemma: if $e \to e'$ and $e' \Downarrow v$ by a derivation with $k$ computing nodes, then $e \Downarrow v$ with $k + 1$. By induction on the step. If it is $(\lambda x.\,e_0)\,v_2 \to e_0[x := v_2]$, build the [application](#def-b3-lambda-calculus-terms) node from $\lambda x.\,e_0 \Downarrow \lambda x.\,e_0$, $v_2 \Downarrow v_2$ and the given derivation. If it is $e_1\,e_2 \to e_1'\,e_2$ with $e_1 \to e_1'$, the derivation of $e_1'\,e_2 \Downarrow v$ contains $e_1' \Downarrow \lambda x.\,e_0$; by induction $e_1 \Downarrow \lambda x.\,e_0$ 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 $e \to^* v$, starting from $v \Downarrow v$. ∎

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 $\Omega$ is an infinite sequence, while $\Omega$ has no derivation at all. [Big-step semantics](#def-b3-lambda-calculus-semantics) cannot tell a loop from a stuck program, both having no derivation; [small-step semantics](#def-b3-lambda-calculus-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](#def-b3-lambda-calculus-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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation) is held to the interpreter of chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis) in this way.

**History — Functions as the foundation.**

Alonzo Church introduced the $\lambda$-notation in 1932, in a system meant as a foundation of logic. In 1936 he and J. Barkley Rosser proved the [confluence](#def-b3-lambda-calculus-rewriting) theorem that bears their names. Max Newman’s lemma appeared in 1942, in a paper on equivalence defined by combinatorial rules. Nicolaas [de Bruijn](#def-b3-lambda-calculus-debruijn)’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 of Exercise 5.1.**

$\{y\}$; $\{x\}$ (the last $x$ is outside the [abstraction](#def-b3-lambda-calculus-terms)); $\{w, z\}$ (`exercise_1_free_variables`).

**Exercise 5.2 ★.**

Which of these pairs are $\alpha$-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](#def-b3-lambda-calculus-debruijn) form of each term.

**Solution of Exercise 5.2.**

The first pair is $\alpha$-equivalent: both are $\lambda.\,\lambda.\,1\;0$. The second is not: $\lambda.\,\lambda.\,1\;0$ against $\lambda.\,\lambda.\,0\;1$. The third is not: in `\x. x z` the $z$ is free, giving $\lambda.\,0\;z$, while `\z. z z` is $\lambda.\,0\;0$; renaming $x$ to $z$ would capture the free $z$ (`exercise_2_alpha_equivalence`).

**Exercise 5.3 ★.**

Reduce `(\x. \y. x y) y` by one $\beta$-step. What does a substitution that ignores capture give, and why is it wrong?

**Solution of Exercise 5.3.**

The test `exercise_3_capture_avoided` checks the answer. One step gives `\y'. y y'`, since the bound $y$ is renamed before the free $y$ 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 $y$ 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 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 $\mathit{succ}$ and $\mathit{plus}$ do not depend on the numbers (`exercise_4_predict_church_lines`).

**Exercise 5.5 ★★.**

A first version of `subst` handled [abstractions](#def-b3-lambda-calculus-terms) 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 of Exercise 5.5.**

Take `\a. (\x. \y. x) a`, whose [normal form](#def-b3-lambda-calculus-beta) is `\a. \y. a`. Normal order reduces the [redex](#def-b3-lambda-calculus-beta) under `\a`; its argument is index 0, shifted to 1 by `beta` before the substitution. Under `\y` the body’s $x$ 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](#def-b3-lambda-calculus-beta)’s $\lambda$ disappears points at `y`. The result is `\a. \y. y`. The fix shifts the substituted term under each $\lambda$: `Lam(x, b) => Lam(x.clone(), Box::new(subst(j + 1, &shift(1, 0, s), b)))`, as in [Listing 5.2](#lst-b3-lambda-calculus-subst) (`exercise_5_shifting_matters` shows both results).

**Exercise 5.6 ★★.**

With the definitions of [Listing 5.4](#lst-b3-lambda-calculus-encode) and $\mathit{sub} = \lambda m.\,\lambda n.\,n\ \mathit{pred}\ m$, which computes $\max(m - n, 0)$, write $\mathit{is\_zero}$, which maps $c_0$ to $\mathit{true}$ and every other numeral to $\mathit{false}$, and $\mathit{eq}$, which tests two numerals for equality. Test them on all numerals up to 5.

**Solution of Exercise 5.6.**

$\mathit{is\_zero} = \lambda n.\,n\,(\lambda x.\,\mathit{false})\,\mathit{true}$: zero [applications](#def-b3-lambda-calculus-terms) leave $\mathit{true}$, and one or more replace it by $\mathit{false}$. With $\mathit{and} = \lambda p.\,\lambda q.\,p\,q\,\mathit{false}$, $\mathit{eq} = \lambda m.\,\lambda n.\,\mathit{and}\,(\mathit{is\_zero}\,(\mathit{sub}\,m\,n))\,(\mathit{is\_zero}\,(\mathit{sub}\,n\,m))$: since subtraction stops at zero, both differences are zero exactly when $m = n$. 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](#def-b3-lambda-calculus-beta), they lead it to the same one. Then reduce `plus c2 c3` by [call by name](#def-b3-lambda-calculus-strategy): where does it stop, and why does this not contradict what you just proved?

**Solution of Exercise 5.7.**

If $M \to_\beta^* N_1$ by one strategy and $M \to_\beta^* N_2$ by another, both [normal forms](#def-b3-lambda-calculus-beta), then both are reducts of $M$, and [Corollary 5.8](#cor-b3-lambda-calculus-unique) gives $N_1 = N_2$ up to $\alpha$-equivalence: a strategy only chooses among $\beta$-steps. [Call by name](#def-b3-lambda-calculus-strategy) 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 $\lambda$, so it stops at an [abstraction](#def-b3-lambda-calculus-terms) that is not in [normal form](#def-b3-lambda-calculus-beta). There is no contradiction: the result was about strategies that reach a [normal form](#def-b3-lambda-calculus-beta), and this one has not; normal order, continuing from there, reaches $c_5$.

**Exercise 5.8 ★★.**

Count the $\beta$-steps that normal order takes to reduce $\mathit{mult}\,c_m\,c_n$ to [normal form](#def-b3-lambda-calculus-beta), as a function of $m$ and $n$, and explain why $n$ does not appear.

**Solution of Exercise 5.8.**

$2m + 3$ (`exercise_8_mult_steps`, for $m, n \le 6$). Two steps substitute $c_m$ and $c_n$, giving $\lambda f.\,c_m\,(c_n\,f)$. One step unfolds $c_m$: $\lambda f.\,\lambda x.\,(c_n\,f)\,((c_n\,f)\,(\cdots x))$, with $m$ copies of $c_n\,f$. Normal order then takes the outermost copy: $c_n\,f \to \lambda x'.\,f^n\,x'$ in one step, and applying it to its argument is a second; and so on for each of the $m$ copies. The number $n$ does not appear because one $\beta$-step substitutes $f$ into all $n$ 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 $\mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to^* v$ holds exactly when $e_1 \to^* \mathtt{true}$ and $e_2 \to^* v$, or $e_1 \to^* \mathtt{false}$ and $e_3 \to^* v$. Deduce the big-step rules of `if`.

**Solution of Exercise 5.9.**

Write $e = \mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3$. If $e_1$ is not a value, the only rule that applies to $e$ is the congruence rule, which steps $e_1$ and keeps the shape. So a reduction $e \to^* v$ begins with steps of $e_1$, as long as $e_1$ is not a value; it must reach a value $v_1$, since otherwise $e$ keeps its shape and never becomes the value $v$. If $v_1$ is neither $\mathtt{true}$ nor $\mathtt{false}$, $e$ is stuck. If it is $\mathtt{true}$, the next step gives $e_2$, and the rest is $e_2 \to^* v$; likewise for $\mathtt{false}$ and $e_3$. Conversely, the congruence rule lifts $e_1 \to^* \mathtt{true}$ to $e \to^* \mathtt{if}\ \mathtt{true}\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3$, one step gives $e_2$, and $e_2 \to^* v$. By [Theorem 5.14](#thm-b3-lambda-calculus-agree), $\to^*$ to a value is $\Downarrow$, which gives the two big-step rules: $e_1 \Downarrow \mathtt{true}$ and $e_2 \Downarrow v$ give $e \Downarrow v$; $e_1 \Downarrow \mathtt{false}$ and $e_3 \Downarrow v$ give $e \Downarrow v$.

**Exercise 5.10 ★★★.**

On the set $\{a, b, c, d\}$, let $b \to a$, $b \to c$, $c \to b$ and $c \to d$. Show that this system is locally [confluent](#def-b3-lambda-calculus-rewriting) but not [confluent](#def-b3-lambda-calculus-rewriting), and say which hypothesis of Newman’s lemma fails. Then prove that the measure used for the rules of $\mathit{add}$ in this chapter decreases when a rule is applied inside a larger term, not only at the top.

**Solution of Exercise 5.10.**

Local [confluence](#def-b3-lambda-calculus-rewriting): from $b$, the reducts $a$ and $c$ meet at $a$, since $c \to b \to a$; from $c$, the reducts $b$ and $d$ meet at $d$, since $b \to c \to d$. The other elements have at most one reduct. Not [confluent](#def-b3-lambda-calculus-rewriting): $b \to a$ and $b \to c \to d$, and $a$ and $d$ are distinct [normal forms](#def-b3-lambda-calculus-beta). Termination fails: $b \to c \to b \to \cdots$. In context: $w$ is strictly increasing in each argument ($w(s(t)) = w(t) + 1$, $w(\mathit{add}(t, u)) = 2w(t) + w(u)$), so if $w(t) > w(t')$, then $w(C[t]) > w(C[t'])$ for every context $C$, by induction on the depth of the hole in $C$. A rule applied anywhere therefore decreases the weight of the whole term.

**Exercise 5.11 ★★★.**

Prove that $\Omega$ has no [normal form](#def-b3-lambda-calculus-beta). Show that $K\,I\,\Omega$, with $K = \lambda x.\,\lambda y.\,x$ and $I = \lambda z.\,z$, has one, that normal order reaches it in two steps, and that [call by value](#def-b3-lambda-calculus-strategy) never does.

**Solution of Exercise 5.11.**

$\Omega$ has exactly one [redex](#def-b3-lambda-calculus-beta), itself (its two parts are [abstractions](#def-b3-lambda-calculus-terms) in [normal form](#def-b3-lambda-calculus-beta)), and contracting it gives $\Omega$ again. So every reduction from $\Omega$ is $\Omega \to \Omega \to \cdots$, and every term on it contains a [redex](#def-b3-lambda-calculus-beta): no [normal form](#def-b3-lambda-calculus-beta). Normal order: $K\,I\,\Omega = ((\lambda x.\,\lambda y.\,x)\,I)\,\Omega \to (\lambda y.\,I)\,\Omega \to I$, two steps, and $I$ is a [normal form](#def-b3-lambda-calculus-beta). [Call by value](#def-b3-lambda-calculus-strategy): $K\,I \to \lambda y.\,I$, a value, but then the argument $\Omega$ must be reduced to a value before the [redex](#def-b3-lambda-calculus-beta) $(\lambda y.\,I)\,\Omega$ may be contracted, and it never becomes one (`exercise_11_omega`). By [Corollary 5.8](#cor-b3-lambda-calculus-unique), $I$ is the only [normal form](#def-b3-lambda-calculus-beta) of $K\,I\,\Omega$; [call by value](#def-b3-lambda-calculus-strategy) simply never reaches it.

**Exercise 5.12 ★★★.**

The Krivine machine evaluates by [call by name](#def-b3-lambda-calculus-strategy) without substitution. Its state is a term, an environment (a list of closures, one per enclosing $\lambda$) and a stack of closures (pending arguments), where a closure is a term with its environment. An [application](#def-b3-lambda-calculus-terms) pushes its argument, as a closure, and continues with the function; an [abstraction](#def-b3-lambda-calculus-terms) pops a closure into its environment and continues with its body; a variable $k$ continues with the $k$-th closure of the environment. Implement it on [de Bruijn](#def-b3-lambda-calculus-debruijn) terms, with a function that reads a closure back as a term, and test that it reaches the same term as [call by name](#def-b3-lambda-calculus-strategy), in the same number of $\beta$-steps.

**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](#def-b3-lambda-calculus-terms) 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 $\lambda$’s crossed; the pending arguments are applied to it. `exercise_12_krivine_matches_call_by_name` runs eight terms, Church arithmetic and $K\,I\,\Omega$ among them: the read-back term is $\alpha$-equivalent to the result of [call by name](#def-b3-lambda-calculus-strategy), and the number of pops equals the number of $\beta$-steps, since each pop is exactly the contraction [call by name](#def-b3-lambda-calculus-strategy) 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](#def-b3-lambda-calculus-church) are a complete arithmetic: every computable function on numbers can be written with them. This problem measures what it costs, counting $\beta$-steps to [normal form](#def-b3-lambda-calculus-beta), under normal order (the strategy that always finds a [normal form](#def-b3-lambda-calculus-beta)) 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
```

***Output 5.4.** $\beta$-steps to [normal form](#def-b3-lambda-calculus-beta) under normal order (`nor`) and applicative order (`app`); `exp c2 c0` is left out, its [normal form](#def-b3-lambda-calculus-beta) `\x. x` not being a numeral.*

**Part I — Numerals and addition.**

1. Write $c_3$ , and reduce $\mathit{succ}\,c_2$ to [normal form](#def-b3-lambda-calculus-beta) by hand, counting the steps.
2. Reduce $\mathit{plus}\,c_2\,c_3$ by normal order. Why do the counts of [Output 5.1](#out-b3-lambda-calculus-church) for $\mathit{plus}$ not depend on the numbers?
3. Is the number of $\beta$ -steps a fair measure of the work? What does each step of $\mathit{plus}\,c_m\,c_n$ copy, and how large is the result?
4. How many symbols does $c_n$ have? Compare with the binary representation of $n$ .
5. Show that $\lambda m.\,\lambda n.\,m\ \mathit{succ}\ n$ also computes $m + n$ .
6. Why does that second addition need more steps than $\mathit{plus}$ as $m$ grows?

**Part II — Multiplication and exponentiation.**

7. From [Output 5.4](#out-b3-lambda-calculus-pb) , give the counts for $\mathit{mult}\,c_n\,c_3$ as a formula, and check it on two lines.
8. Give the counts for $\mathit{exp}\,c_2\,c_n$ under both strategies as formulas.
9. Explain the doubling under normal order: what does normal order copy that applicative order has already reduced?
10. Is normal order always slower? Give a term for which it takes fewer steps than applicative order.
11. What size does the [normal form](#def-b3-lambda-calculus-beta) of $\mathit{exp}\,c_2\,c_n$ have? Does its step count, under either strategy, measure the work of writing it out?
12. Which strategy would you choose for a calculator built on [Church numerals](#def-b3-lambda-calculus-church) , and what would call by need change?

**Part III — The predecessor.**

13. Show that after $k \ge 1$ [applications](#def-b3-lambda-calculus-terms) of the step $(a, b) \mapsto (b, b + 1)$ to $(0, 0)$ , the pair is $(k - 1, k)$ .
14. Why does $\mathit{pred}\,c_0$ give $c_0$ ?
15. From [Output 5.4](#out-b3-lambda-calculus-pb) , give the normal-order count of $\mathit{pred}\,c_n$ for $n \ge 1$ as a formula.
16. How many steps does each round of the step take under normal order? Where do the remaining ones go?
17. Give the applicative-order count for $n \ge 2$ as a formula. Which strategy wins for large $n$ ?
18. Compare with the cost of a predecessor on binary numbers. What has the encoding cost?

**Part IV — Subtraction.**

19. Show that $\mathit{sub}\,c_m\,c_n = c_n\ \mathit{pred}\ c_m$ reduces to $c_{\max(m - n, 0)}$ .
20. From the column `sub 10 n` , compute the differences between consecutive normal-order counts. What do you notice?
21. Suppose the $k$ -th predecessor, for $k = 1, \dots, n$ , costs as much as $\mathit{pred}$ applied to the numeral $c_{m - k + 1}$ , plus 4 steps in all to unfold $\mathit{sub}$ . Derive a formula for the count when $1 \le n \le m$ , and check it against the table.
22. Under normal order, the predecessors are applied to terms that are not yet numerals. Why does the assumption of the previous question still hold?
23. What is the order of growth of the count in $m$ and $n$ ? At $m = n$ ?
24. Sum up: give the cost of $\mathit{pred}$ and of $\mathit{sub}$ under normal order, and say what a machine integer would cost instead.

**Solution of Problem 5.1.**

The formulas are asserted in `tests/pb_test.rs`.

**1.** $c_3 = \lambda f.\,\lambda x.\,f\,(f\,(f\,x))$. Then, in 3 steps,

$$
\mathit{succ}\,c_2 \to \lambda f.\,\lambda x.\,f\,(c_2\,f\,x) \to \lambda f.\,\lambda x.\,f\,((\lambda x'.\,f\,(f\,x'))\,x) \to \lambda f.\,\lambda x.\,f\,(f\,(f\,x)).
$$

**2.** Two steps substitute the numerals: $\lambda f.\,\lambda x.\,c_2\,f\,(c_3\,f\,x)$. Then $c_2\,f$ unfolds and is applied (2 steps), giving $f\,(f\,(c_3\,f\,x))$, and $c_3\,f\,x$ 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 $\mathit{plus}\,c_m\,c_n$ substitute $f$ and $x$ into bodies of sizes about $m$ and $n$, and the result has size $\Theta(m + n)$: the work is at least linear, the step count constant.

**4.** Two $\lambda$’s and $n$ [applications](#def-b3-lambda-calculus-terms) of $f$, so $\Theta(n)$ symbols, against $\lfloor \log_2 n \rfloor + 1$ bits in binary: numerals are unary.

**5.** $c_m\ \mathit{succ}\ c_n \to^* \mathit{succ}\,(\mathit{succ}\,(\cdots(\mathit{succ}\,c_n)))$ with $m$ [applications](#def-b3-lambda-calculus-terms), which is $c_{n+m}$ by induction on $m$, since $\mathit{succ}\,c_k \to^* c_{k+1}$.

**6.** It applies $\mathit{succ}$ $m$ times, at 3 steps each, so it takes $3m + 4$ steps whatever $n$ is, against a constant 6 for $\mathit{plus}$, which moves all of $c_m$’s [applications](#def-b3-lambda-calculus-terms) of $f$ in one substitution.

**7.** $2n + 3$ under both strategies: 3, 5, 7, 9, …; for instance $n = 4$ gives 11 and $n = 10$ gives 23.

**8.** Normal order: $2^{n+1}$ (4, 8, 16, 32, 64). Applicative order: $3n + 1$ (4, 7, 10, 13, 16).

**9.** $\mathit{exp}\,c_2\,c_n$ becomes $c_n\,c_2$, which unfolds to $\lambda x.\,c_2\,(c_2\,(\cdots(c_2\,x)))$. Normal order reduces the outermost $c_2$ first; $c_2$ 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 $c_2\,x$ first, to a [normal form](#def-b3-lambda-calculus-beta), so each level costs 3 steps on an argument already in [normal form](#def-b3-lambda-calculus-beta).

**10.** No. On $K\,I\,\Omega$ normal order takes 2 steps and applicative order never stops; on $(\lambda x.\,y)\,M$ normal order takes one step and applicative order first reduces $M$, at any cost.

**11.** The [normal form](#def-b3-lambda-calculus-beta) is $c_{2^n}$, of size $\Theta(2^n)$. The $3n + 1$ 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](#def-b3-lambda-calculus-beta) while removing the duplicated work.

**13.** By induction on $k$: one step takes $(0, 0)$ to $(0, 1)$; if the pair is $(k - 1, k)$, the step gives $(k, k + 1)$.

**14.** $c_0$ applies the step zero times, leaving $(0, 0)$, whose first component is $c_0$.

**15.** $10n + 6$: 16, 26, 36, …, 106 ($\mathit{pred}\,c_0$ takes 9).

**16.** 10 steps per round of the step: building the new pair and computing $\mathit{succ}$ of the second component. The remaining 6 are a constant: unfolding $\mathit{pred}$, applying the numeral to the step and the initial pair, and selecting the first component at the end.

**17.** $9n + 16$ for $n \ge 2$ (34, 43, …, 106; 23 for $n = 1$, 14 for $n = 0$). Normal order is cheaper up to $n = 9$, the two meet at $n = 10$ (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: $O(\log n)$ bit operations at worst, a constant on average, and one instruction on a machine word. The unary encoding costs a factor of $n$.

**19.** $c_n\ \mathit{pred}\ c_m \to^* \mathit{pred}^n\,c_m$, and by induction on $n$, using $\mathit{pred}\,c_0 = c_0$ and $\mathit{pred}\,c_{k+1} = c_k$, this is $c_{\max(m - n, 0)}$.

**20.** 106, 96, 86, 76, 66, 56, 46, 36, 26, 16: they decrease by 10, and each is the cost of $\mathit{pred}$ on $c_{10}, c_9, \dots, c_1$.

**21.** $4 + \sum_{k=1}^{n} \bigl(10(m - k + 1) + 6\bigr) = 4 + 10mn - 5n(n - 1) + 6n = 10mn - 5n^2 + 11n + 4$. For $m = 10$: $n = 3$ gives $300 - 45 + 33 + 4 = 292$, $n = 10$ gives 614, as in the table (the test checks all $n \le m \le 12$).

**22.** $\mathit{pred} = \lambda n.\,\mathit{fst}\,(n\ \mathit{step}\ (0, 0))$ 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.** $\Theta(mn)$ for $1 \le n \le m$; at $m = n$, $5n^2 + 11n + 4 = \Theta(n^2)$.

**24.** Under normal order, $\mathit{pred}\,c_n$ takes $10n + 6$ $\beta$-steps, $\Theta(n)$, and $\mathit{sub}\,c_m\,c_n$ takes $10mn - 5n^2 + 11n + 4$, $\Theta(mn)$. A machine integer subtracts in one instruction: the $\lambda$-calculus can compute everything, at a price that only matters once one counts.
