计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本: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 ∀x. φ\forall x.\,\varphi, the quantifier binds the occurrences of xx 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∣λx. M∣M MM ::= x \mid \lambda x.\,M \mid M\,M. A term λx. M\lambda x.\,M is an abstraction: the function that maps xx to MM. A term M NM\,N is an application: the function MM called with the argument NN.

Application associates to the left, so f a bf\,a\,b is (f a) b(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 λx. λy. x y\lambda x.\,\lambda y.\,x\,y is λx. (λy. (x y))\lambda x.\,(\lambda y.\,(x\,y)). In code we write \x. M for λx. M\lambda x.\,M, and \x y. M for λx. λy. M\lambda x.\,\lambda y.\,M. A λ\lambda binds its variable in its body exactly as a quantifier does in logic: in λx. x y\lambda x.\,x\,y the occurrence of xx is bound and yy 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: λx. x y\lambda x.\,x\,y and λz. z y\lambda z.\,z\,y are, λx. x y\lambda x.\,x\,y and λy. y y\lambda y.\,y\,y are not. The capture-avoiding substitution M[x:=N]M[x := N] replaces the free occurrences of xx in MM by NN, after renaming the bound variables of MM that would otherwise capture a free variable of NN.

Capture is the whole difficulty. Substituting yy for xx in λy. x\lambda y.\,x naively gives λy. y\lambda y.\,y, the identity, where we wanted the function that ignores its argument and returns yy. The correct result renames first: λy′. y\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 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 λx. λy. x y\lambda x.\,\lambda y.\,x\,y becomes λ. λ. 1  0\lambda.\,\lambda.\,1\;0.

Two α\alpha-equivalent terms have the same de Bruijn form, so α\alpha-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,
    }
}
Listing 5.1. λ\lambda-terms with de Bruijn 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.
A term as a tree, each variable joined to its binder (dashed). The index counts the λ\lambda nodes crossed on the way up: from yy the path meets λz\lambda z first, so yy is 1, and so is xx, which meets λy\lambda y.

Substitution must now keep indices right. When a term NN 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 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))
}
Listing 5.2. Shifting and substitution on de Bruijn 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 (λx. M) N(\lambda x.\,M)\,N. β\beta-reduction replaces one redex by M[x:=N]M[x := N], anywhere in a term; we write M→βM′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 (λx. λy. x y) y(\lambda x.\,\lambda y.\,x\,y)\,y reduces in one step to λy′. y y′\lambda y'.\,y\,y', renaming to avoid capture. Some terms have no normal form: Ω=(λx. x x) (λx. x x)\Omega = (\lambda x.\,x\,x)\,(\lambda x.\,x\,x) 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 λ\lambda. Call by name does the same but never reduces under a λ\lambda or inside an argument. Call by value reduces a redex (λx. M) N(\lambda x.\,M)\,N only once NN is a value (here, an abstraction), 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 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 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)
                }
            }
        }
    }
}
Listing 5.3. One step of each strategy. Normal order and call by name contract a redex at the top before looking inside; call by value 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 even stops early, at a term whose head is the free variable aa, 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.
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 reduces it once, before the copy.

Every path that ends, ends at a aa\,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 AA 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→∗ba \to^* b and a→∗ca \to^* c, there is a dd with b→∗db \to^* d and c→∗dc \to^* d; locally confluent if this holds whenever a→ba \to b and a→ca \to c in one step each; terminating if there is no infinite chain a0→a1→⋯a_0 \to a_1 \to \cdots.

Theorem 5.7 (Church–Rosser)

β\beta-reduction is confluent.

Proof. Admitted at this level. ∎

Local confluence is not enough here, since β\beta-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 →β∗\to_\beta^*.

Corollary 5.8

A λ\lambda-term has at most one normal form, up to α\alpha-equivalence.

Proof. If M→β∗N1M \to_\beta^* N_1 and M→β∗N2M \to_\beta^* N_2 with both in normal form, confluence gives PP with N1→β∗PN_1 \to_\beta^* P and N2→β∗PN_2 \to_\beta^* P. A normal form reduces only to itself, so N1=P=N2N_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, 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 (λx. λy. y) Ω(\lambda x.\,\lambda y.\,y)\,\Omega it reduces Ω\Omega 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 “bb is reachable from aa 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 aa in one or more steps, and prove it for aa. The property is: every two reducts of aa have a common reduct.

Let a→∗ba \to^* b and a→∗ca \to^* c. If either reduction is empty, say a=ba = b, take d=cd = c. Otherwise write a→b1→∗ba \to b_1 \to^* b and a→c1→∗ca \to c_1 \to^* c. By local confluence, there is ee with b1→∗eb_1 \to^* e and c1→∗ec_1 \to^* e. Now b1b_1 is a reduct of aa, so the induction hypothesis applies to it: bb and ee, both reducts of b1b_1, have a common reduct ff. Likewise c1c_1 is a reduct of aa, and ff and cc are both reducts of c1c_1 (since c1→∗e→∗fc_1 \to^* e \to^* f), so they have a common reduct dd. Then b→∗f→∗db \to^* f \to^* d and c→∗dc \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.
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 b1b_1 and c1c_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 add(0,y)→y\mathit{add}(0, y) \to y and add(s(x),y)→s(add(x,y))\mathit{add}(s(x), y) \to s(\mathit{add}(x, y)) define addition on numbers written with 00 and a successor ss. Give each term the weight ww with w(0)=1w(0) = 1, w(s(t))=w(t)+1w(s(t)) = w(t) + 1, w(add(t,u))=2w(t)+w(u)w(\mathit{add}(t, u)) = 2w(t) + w(u): the first rule removes at least w(y)+2−w(y)=2w(y) + 2 - w(y) = 2, the second 2(w(x)+1)+w(y)−2w(x)−w(y)−1=12(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, 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 λ\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 true=λa. λb. a\mathit{true} = \lambda a.\,\lambda b.\,a and false=λa. λb. b\mathit{false} = \lambda a.\,\lambda b.\,b: a boolean chooses between two arguments. The Church numeral of nn is cn=λf. λx. f (f (⋯(f x)))c_n = \lambda f.\,\lambda x.\,f\,(f\,(\cdots(f\,x))), with nn applications of ff: the number nn is the operation “do something nn times”.

A conditional needs no keyword: b M Nb\,M\,N is MM when bb is true\mathit{true} and NN when it is false\mathit{false}. A pair holds its two components until a selector is given to it: pair=λa. λb. λf. f a b\mathit{pair} = \lambda a.\,\lambda b.\,\lambda f.\,f\,a\,b, with fst p=p true\mathit{fst}\,p = p\,\mathit{true}. Arithmetic follows from “nn times”: succ n\mathit{succ}\,n does ff once more than nn does; plus m n\mathit{plus}\,m\,n does ff mm times after nn times; mult m n\mathit{mult}\,m\,n does “ff nn times”, mm times; and exp m n=n m\mathit{exp}\,m\,n = n\,m applies “multiply by mm” nn 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
}
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 nn times, never undo a step. The trick is to count pairs: start from (0,0)(0, 0) and apply nn times the step (a,b)↦(b,b+1)(a, b) \mapsto (b, b + 1). After kk steps the pair is (k−1,k)(k - 1, k) for k≥1k \ge 1, so after nn steps its first component is n−1n - 1 (and 00 when n=0n = 0). 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)
Output 5.1. Six computations, each reduced to normal form under normal order and under applicative order, with the number of β\beta-steps. The normal forms are recognised as numerals; exp c2 c3 prints its numeral with the names x and x', an α\alpha-variant of c8c_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=λfact. λn. if n=0 then 1 else n×fact (n−1).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 gg with F g=gF\,g = g: a fixed point of FF.

Definition 5.12 (Fixed-point combinator)

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

The best known is

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

Indeed Y F→β(λx. F (x x)) (λx. F (x x))→βF ((λx. F (x x)) (λx. F (x x)))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 FF is the term Y FY\,F reduced to in one step. Under call by value, YY is useless: the argument x xx\,x is evaluated before FF is ever entered, and it unfolds again, without end. Wrapping it in a λ\lambda delays it:

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

is a fixed-point combinator for call by value, since λv. x x v\lambda v.\,x\,x\,v 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"),
        }
    }
}
Listing 5.5. The factorial of 5 three ways: through ZZ, through letrec, and through YY, 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
Output 5.2. ZZ computes 120 in 46 steps, letrec in 35; YY never reaches a value, and the term it rewrites keeps growing.

A language does not need ZZ in its programs: letrec f = \x. e1 in e2 is sugar for binding ff to the fixed point of λf. λx. e1\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 ZZ 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; the optional type on a λ\lambda 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>),
}
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→e′e \to e', one step of computation, and a program’s result is the value vv with e→∗ve \to^* v. A big-step semantics defines a relation e⇓ve \Downarrow v, “ee evaluates to vv”, directly, by rules whose premises evaluate the parts of ee.

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 (2+3→52 + 3 \to 5), and its operands are reduced left to right like an application’s.

 (λx. e) v→e[x:=v]e1→e1′e1 e2→e1′ e2e2→e2′v e2→v e2′ let x=v in e→e[x:=v] letrec f=λx. e1 in e2→e2[f:=λx. letrec f=λx. e1 in e1] if true then e2 else e3→e2e1→e1′if e1 then e2 else e3→if e1′ then e2 else e3\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 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()),
    })
}
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:

 v⇓ve1⇓λx. ee2⇓v2e[x:=v2]⇓ve1 e2⇓ve1⇓v1e2[x:=v1]⇓vlet x=e1 in e2⇓ve1⇓truee2⇓vif e1 then e2 else e3⇓ve1⇓n1e2⇓n2e1+e2⇓n1+n2\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’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))),
        },
    }
}
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
 λx. x+1⇓λx. x+1 2⇓2 2⇓2 1⇓12+1⇓3 add(λx. x+1) 2⇓3 app\begin{gather*}{\dfrac{{\dfrac{\ }{\lambda x.\,x + 1 \Downarrow \lambda x.\,x + 1}} \qquad {\dfrac{\ }{2 \Downarrow 2}} \qquad {\dfrac{{\dfrac{\ }{2 \Downarrow 2}} \qquad {\dfrac{\ }{1 \Downarrow 1}}}{2 + 1 \Downarrow 3}\,\scriptstyle\text{add}}}{(\lambda x.\,x + 1)\,2 \Downarrow 3}\,\scriptstyle\text{app}}\end{gather*}
The derivation of (λx. x+1) 2⇓3(\lambda x.\,x + 1)\,2 \Downarrow 3: six nodes, two of which compute (the application and the addition). The small-step run takes exactly two steps: (λx. x+1) 2→2+1→3(\lambda x.\,x + 1)\,2 \to 2 + 1 \to 3.

Output 5.3 runs sum.lam, 3+2+1+03 + 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 ee and a value vv: e→∗ve \to^* v if and only if e⇓ve \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, the premises give, by induction, e1→∗λx. ee_1 \to^* \lambda x.\,e in k1k_1 steps, e2→∗v2e_2 \to^* v_2 in k2k_2 and e[x:=v2]→∗ve[x := v_2] \to^* v in k3k_3. The congruence rules lift the first two reductions to the whole term (a short induction on their length): e1 e2→∗(λx. e) e2→∗(λx. e) v2e_1\,e_2 \to^* (\lambda x.\,e)\,e_2 \to^* (\lambda x.\,e)\,v_2, then one computing step gives e[x:=v2]e[x := v_2], and k3k_3 more give vv. In all k1+k2+1+k3k_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→e′e \to e' and e′⇓ve' \Downarrow v by a derivation with kk computing nodes, then e⇓ve \Downarrow v with k+1k + 1. By induction on the step. If it is (λx. e0) v2→e0[x:=v2](\lambda x.\,e_0)\,v_2 \to e_0[x := v_2], build the application node from λx. e0⇓λx. e0\lambda x.\,e_0 \Downarrow \lambda x.\,e_0, v2⇓v2v_2 \Downarrow v_2 and the given derivation. If it is e1 e2→e1′ e2e_1\,e_2 \to e_1'\,e_2 with e1→e1′e_1 \to e_1', the derivation of e1′ e2⇓ve_1'\,e_2 \Downarrow v contains e1′⇓λx. e0e_1' \Downarrow \lambda x.\,e_0; by induction e1⇓λx. e0e_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→∗ve \to^* v, starting from v⇓vv \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 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 λ\lambda-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.

{y}\{y\}; {x}\{x\} (the last xx is outside the abstraction); {w,z}\{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 form of each term.

Solution

Solution of Exercise 5.2.

The first pair is α\alpha-equivalent: both are λ. λ. 1  0\lambda.\,\lambda.\,1\;0. The second is not: λ. λ. 1  0\lambda.\,\lambda.\,1\;0 against λ. λ. 0  1\lambda.\,\lambda.\,0\;1. The third is not: in \x. x z the zz is free, giving λ. 0  z\lambda.\,0\;z, while \z. z z is λ. 0  0\lambda.\,0\;0; renaming xx to zz would capture the free zz (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

Solution of Exercise 5.3.

The test exercise_3_capture_avoided checks the answer. One step gives \y'. y y', since the bound yy is renamed before the free yy 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 yy 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 succ\mathit{succ} and plus\mathit{plus} 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 xx 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 λ\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 (exercise_5_shifting_matters shows both results).

Exercise 5.6 ★★

With the definitions of Listing 5.4 and sub=λm. λn. n pred m\mathit{sub} = \lambda m.\,\lambda n.\,n\ \mathit{pred}\ m, which computes max⁡(m−n,0)\max(m - n, 0), write is_zero\mathit{is\_zero}, which maps c0c_0 to true\mathit{true} and every other numeral to false\mathit{false}, and eq\mathit{eq}, which tests two numerals for equality. Test them on all numerals up to 5.

Solution

Solution of Exercise 5.6.

is_zero=λn. n (λx. false) true\mathit{is\_zero} = \lambda n.\,n\,(\lambda x.\,\mathit{false})\,\mathit{true}: zero applications leave true\mathit{true}, and one or more replace it by false\mathit{false}. With and=λp. λq. p q false\mathit{and} = \lambda p.\,\lambda q.\,p\,q\,\mathit{false}, eq=λm. λn. and (is_zero (sub m n)) (is_zero (sub n m))\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=nm = 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, 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 M→β∗N1M \to_\beta^* N_1 by one strategy and M→β∗N2M \to_\beta^* N_2 by another, both normal forms, then both are reducts of MM, and Corollary 5.8 gives N1=N2N_1 = N_2 up to α\alpha-equivalence: a strategy only chooses among β\beta-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 λ\lambda, 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 c5c_5.

Exercise 5.8 ★★

Count the β\beta-steps that normal order takes to reduce mult cm cn\mathit{mult}\,c_m\,c_n to normal form, as a function of mm and nn, and explain why nn does not appear.

Solution

Solution of Exercise 5.8.

2m+32m + 3 (exercise_8_mult_steps, for m,n≤6m, n \le 6). Two steps substitute cmc_m and cnc_n, giving λf. cm (cn f)\lambda f.\,c_m\,(c_n\,f). One step unfolds cmc_m: λf. λx. (cn f) ((cn f) (⋯x))\lambda f.\,\lambda x.\,(c_n\,f)\,((c_n\,f)\,(\cdots x)), with mm copies of cn fc_n\,f. Normal order then takes the outermost copy: cn f→λx′. fn x′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 mm copies. The number nn does not appear because one β\beta-step substitutes ff into all nn 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 if e1 then e2 else e3→∗v\mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to^* v holds exactly when e1→∗truee_1 \to^* \mathtt{true} and e2→∗ve_2 \to^* v, or e1→∗falsee_1 \to^* \mathtt{false} and e3→∗ve_3 \to^* v. Deduce the big-step rules of if.

Solution

Solution of Exercise 5.9.

Write e=if e1 then e2 else e3e = \mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3. If e1e_1 is not a value, the only rule that applies to ee is the congruence rule, which steps e1e_1 and keeps the shape. So a reduction e→∗ve \to^* v begins with steps of e1e_1, as long as e1e_1 is not a value; it must reach a value v1v_1, since otherwise ee keeps its shape and never becomes the value vv. If v1v_1 is neither true\mathtt{true} nor false\mathtt{false}, ee is stuck. If it is true\mathtt{true}, the next step gives e2e_2, and the rest is e2→∗ve_2 \to^* v; likewise for false\mathtt{false} and e3e_3. Conversely, the congruence rule lifts e1→∗truee_1 \to^* \mathtt{true} to e→∗if true then e2 else e3e \to^* \mathtt{if}\ \mathtt{true}\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3, one step gives e2e_2, and e2→∗ve_2 \to^* v. By Theorem 5.14, →∗\to^* to a value is ⇓\Downarrow, which gives the two big-step rules: e1⇓truee_1 \Downarrow \mathtt{true} and e2⇓ve_2 \Downarrow v give e⇓ve \Downarrow v; e1⇓falsee_1 \Downarrow \mathtt{false} and e3⇓ve_3 \Downarrow v give e⇓ve \Downarrow v.

Exercise 5.10 ★★★

On the set {a,b,c,d}\{a, b, c, d\}, let b→ab \to a, b→cb \to c, c→bc \to b and c→dc \to d. 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 add\mathit{add} 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 bb, the reducts aa and cc meet at aa, since c→b→ac \to b \to a; from cc, the reducts bb and dd meet at dd, since b→c→db \to c \to d. The other elements have at most one reduct. Not confluent: b→ab \to a and b→c→db \to c \to d, and aa and dd are distinct normal forms. Termination fails: b→c→b→⋯b \to c \to b \to \cdots. In context: ww is strictly increasing in each argument (w(s(t))=w(t)+1w(s(t)) = w(t) + 1, w(add(t,u))=2w(t)+w(u)w(\mathit{add}(t, u)) = 2w(t) + w(u)), so if w(t)>w(t′)w(t) > w(t'), then w(C[t])>w(C[t′])w(C[t]) > w(C[t']) for every context CC, by induction on the depth of the hole in CC. A rule applied anywhere therefore decreases the weight of the whole term.

Exercise 5.11 ★★★

Prove that Ω\Omega has no normal form. Show that K I ΩK\,I\,\Omega, with K=λx. λy. xK = \lambda x.\,\lambda y.\,x and I=λz. zI = \lambda z.\,z, has one, that normal order reaches it in two steps, and that call by value never does.

Solution

Solution of Exercise 5.11.

Ω\Omega has exactly one redex, itself (its two parts are abstractions in normal form), 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: no normal form. Normal order: K I Ω=((λx. λy. x) I) Ω→(λy. I) Ω→IK\,I\,\Omega = ((\lambda x.\,\lambda y.\,x)\,I)\,\Omega \to (\lambda y.\,I)\,\Omega \to I, two steps, and II is a normal form. Call by value: K I→λy. IK\,I \to \lambda y.\,I, a value, but then the argument Ω\Omega must be reduced to a value before the redex (λy. I) Ω(\lambda y.\,I)\,\Omega may be contracted, and it never becomes one (exercise_11_omega). By Corollary 5.8, II is the only normal form of K I ΩK\,I\,\Omega; 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 λ\lambda) 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 kk continues with the kk-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 β\beta-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 λ\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 ΩK\,I\,\Omega among them: the read-back term is α\alpha-equivalent to the result of call by name, and the number of pops equals the number of β\beta-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 β\beta-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
Output 5.4. β\beta-steps to normal form under normal order (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.

  1. Write c3c_3, and reduce succ c2\mathit{succ}\,c_2 to normal form by hand, counting the steps.
  2. Reduce plus c2 c3\mathit{plus}\,c_2\,c_3 by normal order. Why do the counts of Output 5.1 for plus\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 plus cm cn\mathit{plus}\,c_m\,c_n copy, and how large is the result?
  4. How many symbols does cnc_n have? Compare with the binary representation of nn.
  5. Show that λm. λn. m succ n\lambda m.\,\lambda n.\,m\ \mathit{succ}\ n also computes m+nm + n.
  6. Why does that second addition need more steps than plus\mathit{plus} as mm grows?

Part II — Multiplication and exponentiation.

  1. From Output 5.4, give the counts for mult cn c3\mathit{mult}\,c_n\,c_3 as a formula, and check it on two lines.
  2. Give the counts for exp c2 cn\mathit{exp}\,c_2\,c_n under both strategies as formulas.
  3. Explain the doubling under normal order: what does normal order copy that applicative order has already reduced?
  4. Is normal order always slower? Give a term for which it takes fewer steps than applicative order.
  5. What size does the normal form of exp c2 cn\mathit{exp}\,c_2\,c_n have? Does its step count, under either strategy, measure the work of writing it out?
  6. Which strategy would you choose for a calculator built on Church numerals, and what would call by need change?

Part III — The predecessor.

  1. Show that after k≥1k \ge 1 applications of the step (a,b)↦(b,b+1)(a, b) \mapsto (b, b + 1) to (0,0)(0, 0), the pair is (k−1,k)(k - 1, k).
  2. Why does pred c0\mathit{pred}\,c_0 give c0c_0?
  3. From Output 5.4, give the normal-order count of pred cn\mathit{pred}\,c_n for n≥1n \ge 1 as a formula.
  4. How many steps does each round of the step take under normal order? Where do the remaining ones go?
  5. Give the applicative-order count for n≥2n \ge 2 as a formula. Which strategy wins for large nn?
  6. Compare with the cost of a predecessor on binary numbers. What has the encoding cost?

Part IV — Subtraction.

  1. Show that sub cm cn=cn pred cm\mathit{sub}\,c_m\,c_n = c_n\ \mathit{pred}\ c_m reduces to cmax⁡(m−n,0)c_{\max(m - n, 0)}.
  2. From the column sub 10 n, compute the differences between consecutive normal-order counts. What do you notice?
  3. Suppose the kk-th predecessor, for k=1,…,nk = 1, \dots, n, costs as much as pred\mathit{pred} applied to the numeral cm−k+1c_{m - k + 1}, plus 4 steps in all to unfold sub\mathit{sub}. Derive a formula for the count when 1≤n≤m1 \le n \le m, and check it against the table.
  4. Under normal order, the predecessors are applied to terms that are not yet numerals. Why does the assumption of the previous question still hold?
  5. What is the order of growth of the count in mm and nn? At m=nm = n?
  6. Sum up: give the cost of pred\mathit{pred} and of sub\mathit{sub} 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. c3=λf. λx. f (f (f x))c_3 = \lambda f.\,\lambda x.\,f\,(f\,(f\,x)). Then, in 3 steps,

succ c2→λf. λx. f (c2 f x)→λf. λx. f ((λx′. f (f x′)) x)→λf. λx. f (f (f x)).\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: λf. λx. c2 f (c3 f x)\lambda f.\,\lambda x.\,c_2\,f\,(c_3\,f\,x). Then c2 fc_2\,f unfolds and is applied (2 steps), giving f (f (c3 f x))f\,(f\,(c_3\,f\,x)), and c3 f xc_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 plus cm cn\mathit{plus}\,c_m\,c_n substitute ff and xx into bodies of sizes about mm and nn, and the result has size Θ(m+n)\Theta(m + n): the work is at least linear, the step count constant.

4. Two λ\lambda’s and nn applications of ff, so Θ(n)\Theta(n) symbols, against ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 bits in binary: numerals are unary.

5. cm succ cn→∗succ (succ (⋯(succ cn)))c_m\ \mathit{succ}\ c_n \to^* \mathit{succ}\,(\mathit{succ}\,(\cdots(\mathit{succ}\,c_n))) with mm applications, which is cn+mc_{n+m} by induction on mm, since succ ck→∗ck+1\mathit{succ}\,c_k \to^* c_{k+1}.

6. It applies succ\mathit{succ} mm times, at 3 steps each, so it takes 3m+43m + 4 steps whatever nn is, against a constant 6 for plus\mathit{plus}, which moves all of cmc_m’s applications of ff in one substitution.

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

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

9. exp c2 cn\mathit{exp}\,c_2\,c_n becomes cn c2c_n\,c_2, which unfolds to λx. c2 (c2 (⋯(c2 x)))\lambda x.\,c_2\,(c_2\,(\cdots(c_2\,x))). Normal order reduces the outermost c2c_2 first; c2c_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 c2 xc_2\,x first, to a normal form, so each level costs 3 steps on an argument already in normal form.

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

11. The normal form is c2nc_{2^n}, of size Θ(2n)\Theta(2^n). The 3n+13n + 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 while removing the duplicated work.

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

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

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

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

17. 9n+169n + 16 for n≥2n \ge 2 (34, 43, …, 106; 23 for n=1n = 1, 14 for n=0n = 0). Normal order is cheaper up to n=9n = 9, the two meet at n=10n = 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)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 nn.

19. cn pred cm→∗predn cmc_n\ \mathit{pred}\ c_m \to^* \mathit{pred}^n\,c_m, and by induction on nn, using pred c0=c0\mathit{pred}\,c_0 = c_0 and pred ck+1=ck\mathit{pred}\,c_{k+1} = c_k, this is cmax⁡(m−n,0)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 pred\mathit{pred} on c10,c9,…,c1c_{10}, c_9, \dots, c_1.

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

22. pred=λn. fst (n step (0,0))\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. Θ(mn)\Theta(mn) for 1≤n≤m1 \le n \le m; at m=nm = n, 5n2+11n+4=Θ(n2)5n^2 + 11n + 4 = \Theta(n^2).

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

本章定义的术语

在术语表中查看全部 1050 个术语