---
title: "Type Systems and Type Inference"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 6
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/6-type-systems-and-type-inference
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 6 — Type Systems and Type Inference

Chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis) checked Moor’s types with a few dozen lines of Rust and proved, for one operator, that the check keeps booleans out of additions. This chapter does it properly, for the $\lambda$-language of chapter [5](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#ch-b3-lambda-calculus): rules that say which programs have which types, a theorem that says well-typed programs never get stuck, and an algorithm that finds the types of a program that declares none, the most general ones, which is how programmers in languages with inference can leave most types unwritten. It ends with a [type system](#def-b3-type-systems-type-system) that tracks not what a value is but how often it may be used: Rust’s.

## 6.1 Typing rules and derivations

**Definition 6.1 (Type system).**

A *type system* is a set of rules that assigns types to the phrases of a language and rejects the programs to which it can assign none, so as to rule out a class of errors before the program runs.

**Definition 6.2 (Typing context, judgement, rule, derivation).**

A *typing context* $\Gamma$ is a finite list of bindings $x : \tau$ of variables to types; a later binding of a name hides an earlier one. A *typing judgement* $\Gamma \vdash e : \tau$ asserts that in the context $\Gamma$, the expression $e$ has type $\tau$. A *typing rule* derives a judgement from others, its premises. A *typing derivation* is a finite tree of rule applications whose root is the judgement it proves.

The types of the $\lambda$-language are $\tau ::= \mathtt{int} \mid \mathtt{bool} \mid \tau \to \tau \mid \tau \times \tau$, the arrow associating to the right. Here are the rules for its core.

$$
\begin{gather*}{\dfrac{(x : \tau) \in \Gamma}{\Gamma \vdash x : \tau}}\;\textsc{var}

{\dfrac{\Gamma, x : \tau_1 \vdash e : \tau_2}{\Gamma \vdash \lambda x{:}\tau_1.\,e : \tau_1 \to \tau_2}}\;\textsc{abs}

{\dfrac{\Gamma \vdash e_1 : \tau_1 \to \tau_2 \qquad  \Gamma \vdash e_2 : \tau_1}{\Gamma \vdash e_1\,e_2 : \tau_2}}\;\textsc{app}

{\dfrac{\Gamma \vdash e_1 : \tau_1 \qquad  \Gamma, x : \tau_1 \vdash e_2 : \tau_2}{\Gamma \vdash \mathtt{let}\ x = e_1\ \mathtt{in}\ e_2 : \tau_2}}\;\textsc{let}

{\dfrac{\Gamma \vdash e_1 : \mathtt{bool} \qquad  \Gamma \vdash e_2 : \tau \qquad  \Gamma \vdash e_3 : \tau}{\Gamma \vdash \mathtt{if}\ e_1\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 : \tau}}\;\textsc{if}

{\dfrac{\Gamma \vdash e_1 : \mathtt{int} \qquad  \Gamma \vdash e_2 : \mathtt{int}}{\Gamma \vdash e_1 + e_2 : \mathtt{int}}}\;\textsc{op}\end{gather*}
$$

Integer and boolean constants have their obvious types; $-$ and $\times$ are typed like $+$, and $<$ and $==$ take two integers and give a boolean. Equality is restricted to integers so that every well-typed comparison computes: a comparison of two functions would be stuck.

**Definition 6.3 (Simply typed λ\lambdaλ-calculus).**

The *simply typed $\lambda$-calculus* is the $\lambda$-calculus restricted to terms that have a type under rules var , abs and app , with each parameter annotated by its type and a set of base types.

The rules are syntax-directed: for each form of expression, exactly one rule can conclude about it, so a checker needs no search. It walks the tree, and for each node applies the one rule, which is a recursive call per premise ([Listing 6.1](#lst-b3-type-systems-check)). Recording the rule and the premises at each node builds the derivation itself.

```rust
pub fn derive(ctx: &Ctx, e: &E) -> Result<Deriv, String> {
    let node = |rule, ty, premises| {
        Ok(Deriv { rule, ctx: ctx.clone(), e: e.clone(), ty, premises })
    };
    match e {
        E::Int(_) => node("int", Ty::Int, vec![]),
        E::Bool(_) => node("bool", Ty::Bool, vec![]),
        E::Var(x) => match ctx.iter().rev().find(|(y, _)| y == x) {
            Some((_, t)) => node("var", t.clone(), vec![]),
            None => Err(format!("'{x}' is not in the context")),
        },
        E::Lam(x, Some(a), body) => {
            let mut c2 = ctx.clone();
            c2.push((x.clone(), a.clone()));
            let d = derive(&c2, body)?;
            let t = Ty::Fun(Box::new(a.clone()), Box::new(d.ty.clone()));
            node("abs", t, vec![d])
        }
        E::Lam(x, None, _) => Err(format!("the parameter '{x}' has no type")),
        E::App(f, a) => {
            let (df, da) = (derive(ctx, f)?, derive(ctx, a)?);
            match &df.ty {
                Ty::Fun(p, r) if **p == da.ty => {
                    let r = (**r).clone();
                    node("app", r, vec![df, da])
                }
                Ty::Fun(p, _) => {
                    Err(format!("{} expects {}, not {}", show(f), show_ty(p), show_ty(&da.ty)))
                }
                t => Err(format!("{} has type {}, not a function", show(f), show_ty(t))),
            }
        }
```

***Listing 6.1.** The checker of the simply typed core: one arm per rule, one recursive call per premise; each node of the result is one node of the derivation. code/bachelor-3/06-type-systems/listings/check.rs*

```
$ rustc --edition 2021 -O -o derive_demo derive_demo.rs && ./derive_demo
|- (\f: int -> int. f (f 3)) (\x: int. x * 2) : int   [app]
  |- \f: int -> int. f (f 3) : (int -> int) -> int   [abs]
    f: int -> int |- f (f 3) : int   [app]
      f: int -> int |- f : int -> int   [var]
      f: int -> int |- f 3 : int   [app]
        f: int -> int |- f : int -> int   [var]
        f: int -> int |- 3 : int   [int]
  |- \x: int. x * 2 : int -> int   [abs]
    x: int |- x * 2 : int   [op]
      x: int |- x : int   [var]
      x: int |- 2 : int   [int]
11 judgements
```

***Output 6.1.** A [typing derivation](#def-b3-type-systems-judgement) printed with the conclusion first and the premises indented below it. Each line is a judgement, and the rule that proves it is in brackets.*

A derivation is a proof, and the checker is a proof search that never needs to backtrack. Drawn the usual way, with premises above the line, the subtree of [Output 6.1](#out-b3-type-systems-derive) for the argument is the figure below.

*Four judgements, the last four lines of [Output 6.1](#out-b3-type-systems-derive), as a tree. The leaves need no premise: a variable is looked up in the context, a constant has its type.*

## 6.2 Type safety

A [type system](#def-b3-type-systems-type-system) is only worth its rules if they guarantee something. The guarantee is stated against the [small-step semantics](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-semantics) of chapter [5](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#ch-b3-lambda-calculus).

**Definition 6.4 (Type safety, progress, preservation).**

A [type system](#def-b3-type-systems-type-system) is *safe* for a semantics if a well-typed closed program never reaches a stuck term. It is usually proved in two parts. *Progress*: a closed well-typed term is a value or can take a step. *Preservation*: if $\vdash e : \tau$ and $e \to e'$, then $\vdash e' : \tau$. The *canonical forms* of a type are the shapes of its closed values.

**Lemma 6.5 (Canonical forms).**

If $v$ is a value and $\vdash v : \tau$, then: if $\tau = \mathtt{int}$, $v$ is an integer; if $\tau = \mathtt{bool}$, $v$ is $\mathtt{true}$ or $\mathtt{false}$; if $\tau = \tau_1 \to \tau_2$, $v$ is an abstraction; if $\tau = \tau_1 \times \tau_2$, $v$ is a pair of values.

**Proof.** The values are integers, booleans, abstractions and pairs of values, and the rules give each one type form only: the constant rules give $\mathtt{int}$ or $\mathtt{bool}$, abs an arrow, the pair rule a product. So a value of an arrow type, say, can only be an abstraction. ∎

**Theorem 6.6 (Progress).**

If $\vdash e : \tau$, then $e$ is a value or there is $e'$ with $e \to e'$.

**Proof.** By induction on the derivation. A variable cannot be typed in the empty context, and constants and abstractions are values. Consider $e_1\,e_2$, typed by app with $\vdash e_1 : \tau_1 \to \tau_2$ and $\vdash e_2 : \tau_1$. By induction, $e_1$ is a value or steps; if it steps, so does $e_1\,e_2$ by the first congruence rule. Otherwise, if $e_2$ steps, $e_1\,e_2$ does by the second. Otherwise both are values, and by [canonical forms](#def-b3-type-systems-safety) $e_1$ is an abstraction $\lambda x.\,e$, so $e_1\,e_2$ is a [redex](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-beta) and steps to $e[x := e_2]$. For $\mathtt{if}$, $+$, `fst` and the others the argument is the same: either a part steps, or all the parts that are evaluated are values, of the types the rule demands, hence by [canonical forms](#def-b3-type-systems-safety) of the shapes the computing rule needs. ∎

[Preservation](#def-b3-type-systems-safety) needs one lemma: substituting a value of the right type for a variable keeps the type.

**Lemma 6.7 (Substitution).**

If $\Gamma, x : \sigma \vdash e : \tau$ and $\vdash v : \sigma$, then $\Gamma \vdash e[x := v] : \tau$.

The proof is a short induction on the derivation of $e$’s type (exercise [6.7](#exo-b3-type-systems-7)).

**Theorem 6.8 (Preservation).**

If $\vdash e : \tau$ and $e \to e'$, then $\vdash e' : \tau$.

**Proof.** By induction on the derivation of $e \to e'$. For the $\beta$-rule, $(\lambda x.\,e_0)\,v \to e_0[x := v]$: the typing of the [redex](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#def-b3-lambda-calculus-beta) ends with app , above which abs gives $x : \tau_1 \vdash e_0 : \tau$, and the argument has $\vdash v : \tau_1$; the substitution lemma gives $\vdash e_0[x := v] : \tau$. A `let` is the same. For $\mathtt{if}\ \mathtt{true}\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to e_2$, rule if types $e_2$ with $\tau$. For $2 + 3 \to 5$, both sides are integers. For a congruence step, such as $e_1\,e_2 \to e_1'\,e_2$, the induction hypothesis gives $e_1'$ the type of $e_1$, and app applies again. The case of `letrec` is exercise [6.10](#exo-b3-type-systems-10). ∎

**Corollary 6.9.**

A closed well-typed program never gets stuck: every term it reaches is a value or takes a step.

**Proof.** By induction on the number of steps, [preservation](#def-b3-type-systems-safety) keeps every term reached well-typed, and [progress](#def-b3-type-systems-safety) then says it is a value or steps. ∎

![Progress gives each well-typed term a next step unless it is a value; preservation carries the type to the next term. Together they rule out the one bad outcome, a term that is neither a value nor able to step. A run may still go on forever.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-type-systems/fig-50604de02175.svg)

*[Progress](#def-b3-type-systems-safety) gives each well-typed term a next step unless it is a value; [preservation](#def-b3-type-systems-safety) carries the type $\tau$ to the next term. Together they rule out the one bad outcome, a term that is neither a value nor able to step. A run may still go on forever.*

The test `safety_on_sample_programs` checks both properties along entire runs: at every step of five programs, the term is not stuck, and its type has not changed. Safety says nothing about loops, nor about errors the [type system](#def-b3-type-systems-type-system) does not track: a division by zero, an index out of range, are outside it, and a language either defines their result (Moor does) or turns them into checked run-time errors.

## 6.3 Polymorphism

In the simply typed calculus, $\lambda x{:}\mathtt{int}.\,x$ and $\lambda x{:}\mathtt{bool}.\,x$ are two functions. One would like to write the identity once.

**Definition 6.10 (Type variable, type scheme, parametric polymorphism).**

A *type variable* $\alpha$ stands for an unknown type; we print them `'a`, `'b`, …. A *type scheme* $\forall \alpha_1 \dots \alpha_n.\,\tau$ is a type with some of its variables quantified: it stands for every type obtained by replacing them, its *instances*. A function is *parametrically polymorphic* if it has a type scheme, one code for all the instances. *Let-polymorphism* gives schemes to variables bound by `let`, and only types to variables bound by $\lambda$.

So $\mathtt{let}\ \mathit{id} = \lambda x.\,x\ \mathtt{in}\ (\mathit{id}\ 1, \mathit{id}\ \mathtt{true})$ is well typed: $\mathit{id}$ gets $\forall \alpha.\,\alpha \to \alpha$, and its two uses take the instances $\mathtt{int} \to \mathtt{int}$ and $\mathtt{bool} \to \mathtt{bool}$. The same program with $\mathit{id}$ bound by a $\lambda$, $(\lambda \mathit{id}.\,(\mathit{id}\ 1, \mathit{id}\ \mathtt{true}))\,(\lambda x.\,x)$, is rejected: a parameter has one type in the whole body. Two rules express this:

$$
\begin{gather*}{\dfrac{(x : \forall \vec\alpha.\,\tau) \in \Gamma}{\Gamma \vdash x : \tau[\vec\alpha := \vec\tau]}}\;\textsc{inst}

{\dfrac{\Gamma \vdash e_1 : \tau_1 \qquad  \Gamma, x : \forall \vec\alpha.\,\tau_1 \vdash e_2 : \tau_2 \qquad  \vec\alpha \text{ not free in } \Gamma}{\Gamma \vdash \mathtt{let}\ x = e_1\ \mathtt{in}\ e_2 : \tau_2}}\;\textsc{let}\end{gather*}
$$

The side condition matters: a variable that also occurs in the type of something in $\Gamma$ is not free to vary, since that thing fixes it.

The restriction to `let` is what keeps inference decidable: a system where a $\lambda$-bound variable could be used at two types needs annotations. And it leaves some terms untypable for good. In $\lambda x.\,x\,x$, the variable $x$ is applied to itself, so its type $\tau$ must be a function type whose argument is $\tau$ itself: $\tau = \tau \to \tau'$, which no finite type solves.

## 6.4 Unification and inference

**You already know.**

A substitution maps variables to terms; a unifier of two terms is a substitution that makes them equal, and a most general unifier is one of which every other unifier is an instance. The occurs check refuses to bind a variable to a term that contains it (Year 2 volume, predicate logic).

Inference turns typing into equations, and equations into a unification problem over type trees.

**Definition 6.11 (Type substitution, type equation).**

A *type substitution* maps [type variables](#def-b3-type-systems-polymorphism) to types and applies to a type by replacing each of its variables. A *type equation* $\tau_1 \doteq \tau_2$ asks for a type substitution $S$ with $S(\tau_1) = S(\tau_2)$.

For type trees, Robinson’s algorithm is short. To unify two types, apply the substitution found so far to both. If one is a variable $\alpha$, bind it to the other, unless it occurs in it; if both are the same constant, succeed; if both are arrows, or both products, unify the two pairs of children; otherwise fail. [Listing 6.2](#lst-b3-type-systems-unify) keeps the substitution idempotent: when $\alpha := \tau$ is added, $\tau$ is substituted into every binding already present, so applying the substitution once is enough.

```rust
fn bind(s: &mut Subst, a: u32, t: Ty) -> Result<(), String> {
    if t == Ty::Var(a) {
        return Ok(());
    }
    if occurs(a, &t) {
        return Err(format!("{} would have to equal {}, which contains it",
                           show_ty(&Ty::Var(a)), show_ty(&t)));
    }
    let one = Subst::from([(a, t.clone())]);
    for u in s.values_mut() {
        *u = apply(&one, u);
    }
    s.insert(a, t);
    Ok(())
}

/// Extend s so that s(t1) = s(t2), as generally as possible.
pub fn unify(s: &mut Subst, t1: &Ty, t2: &Ty) -> Result<(), String> {
    UNIFY_CALLS.fetch_add(1, Ordering::Relaxed);
    let (a, b) = (apply(s, t1), apply(s, t2));
    match (&a, &b) {
        (Ty::Var(x), _) => bind(s, *x, b.clone()),
        (_, Ty::Var(y)) => bind(s, *y, a.clone()),
        (Ty::Int, Ty::Int) | (Ty::Bool, Ty::Bool) => Ok(()),
        (Ty::Fun(a1, r1), Ty::Fun(a2, r2)) | (Ty::Pair(a1, r1), Ty::Pair(a2, r2)) => {
            unify(s, a1, a2)?;
            unify(s, r1, r2)
        }
        _ => Err(format!("{} is not {}", show_ty(&a), show_ty(&b))),
    }
}
```

***Listing 6.2.** Unification of two types, extending a substitution; `bind` refuses a variable that occurs in its value. code/bachelor-3/06-type-systems/listings/unify.rs*

![Unifying ( a b) × a with ( int bool) × c: left children first gives 'a := int and 'b := bool; the right children are then 'a, already int, and 'c, so 'c := int. Both trees become the tree on the right (unification_of_the_figure).](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-type-systems/fig-5585a501d854.svg)

*Unifying $(\texttt{\textquotesingle a} \to \texttt{\textquotesingle b}) \times \texttt{\textquotesingle a}$ with $(\mathtt{int} \to \mathtt{bool}) \times \texttt{\textquotesingle c}$: left children first gives `'a := int` and `'b := bool`; the right children are then `'a`, already `int`, and `'c`, so `'c := int`. Both trees become the tree on the right (`unification_of_the_figure`).*

**Theorem 6.12 (Unification).**

If $\tau_1$ and $\tau_2$ have a unifier, `unify` returns a most general one; otherwise it fails.

**Proof.** We prove: if `unify` is called with a substitution $S$, and $U$ is any unifier of $S(\tau_1)$ and $S(\tau_2)$ that is an instance of $S$ ($U = R \circ S$ for some $R$), then `unify` succeeds with an $S'$ of which $U$ is still an instance, and $S'$ unifies the two types. The induction is on the number of variables not bound by $S$, then on the size of the types. Write $a = S(\tau_1)$, $b = S(\tau_2)$. If $a$ is a variable $\alpha$ and $b \ne \alpha$, then $U(\alpha) = U(b)$; were $\alpha$ to occur in $b$, $U(b)$ would contain $U(\alpha)$ as a proper subterm, so it could not equal it: the occurs check fails only when there is no unifier. Otherwise $S' = \{\alpha := b\} \circ S$ unifies, and $U$ is an instance of it, since $U$ already sends $\alpha$ to $U(b)$. If both are arrows $a_1 \to a_2$ and $b_1 \to b_2$, then $U$ unifies $a_1$ with $b_1$ and $a_2$ with $b_2$; the first recursive call gives $S_1$ of which $U$ is an instance, and the second call, on smaller types or with fewer unbound variables, gives $S'$. If the two have different constructors, no substitution can make them equal. Taking $S$ empty gives the theorem. ∎

**Definition 6.13 (Type inference, principal type).**

*Type inference* computes a type for an expression whose variables carry no annotations. A *principal type* of a closed expression is a type of which every type it has is an instance.

The algorithm, called W (here in its imperative form, often called J, which keeps one substitution and extends it in place), walks the expression once. A $\lambda$-bound variable gets a fresh [type variable](#def-b3-type-systems-polymorphism). An application $e_1\,e_2$ infers $\tau_1$ and $\tau_2$, takes a fresh $\beta$ and unifies $\tau_1$ with $\tau_2 \to \beta$. A use of a `let`-bound name takes a fresh instance of its scheme; at the `let` itself the inferred type is *generalised*: the variables it still contains, and that no type in the environment mentions, are quantified. A `letrec` binds the function to a fresh variable inside its own body, monomorphically, and generalises after.

```rust
    /// A fresh copy of the scheme's type, its bound variables renamed.
    fn instantiate(&mut self, sc: &Scheme) -> Ty {
        let fresh: Subst = sc.vars.iter().map(|&v| (v, self.fresh())).collect();
        apply(&fresh, &sc.ty)
    }
    /// Quantify the variables of t that are not free in the environment.
    fn gen(&self, env: &Env, t: &Ty) -> Scheme {
        let t = apply(&self.s, t);
        if !self.generalise {
            return mono(t);
        }
        let mut in_env = BTreeSet::new();
        for (_, sc) in env {
            let mut vs = BTreeSet::new();
            type_vars(&apply(&self.s, &sc.ty), &mut vs);
            in_env.extend(vs.into_iter().filter(|v| !sc.vars.contains(v)));
        }
        let mut vs = BTreeSet::new();
        type_vars(&t, &mut vs);
        Scheme { vars: vs.difference(&in_env).copied().collect(), ty: t }
    }
```

***Listing 6.3.** Instantiation renames a scheme’s quantified variables; generalisation quantifies the variables the environment does not mention. code/bachelor-3/06-type-systems/listings/infer.rs*

```rust
    pub fn infer(&mut self, env: &Env, e: &E) -> Result<Ty, String> {
        let t = match e {
            E::Int(_) => Ty::Int,
            E::Bool(_) => Ty::Bool,
            E::Var(x) => match env.iter().rev().find(|(y, _)| y == x) {
                Some((_, sc)) => self.instantiate(&sc.clone()),
                None => return Err(format!("'{x}' is not bound")),
            },
            E::Lam(x, ann, body) => {
                let a = ann.clone().unwrap_or_else(|| self.fresh());
                let mut env2 = env.clone();
                env2.push((x.clone(), mono(a.clone())));
                let r = self.infer(&env2, body)?;
                Ty::Fun(Box::new(a), Box::new(r))
            }
            E::App(f, arg) => {
                let tf = self.infer(env, f)?;
                let ta = self.infer(env, arg)?;
                let r = self.fresh();
                self.unify(&tf, &Ty::Fun(Box::new(ta), Box::new(r.clone())))?;
                r
            }
            E::Let(x, e1, e2) | E::LetRec(x, e1, e2) => {
                let mut env1 = env.clone();
                let rec = matches!(e, E::LetRec(..)).then(|| self.fresh());
                if let Some(a) = &rec {
                    env1.push((x.clone(), mono(a.clone()))); // f is monomorphic in its body
                }
                let t1 = self.infer(&env1, e1)?;
                if let Some(a) = &rec {
                    self.unify(a, &t1)?;
                }
                let sc = self.gen(env, &t1);
                (self.on_let)(x, &sc);
                let mut env2 = env.clone();
                env2.push((x.clone(), sc));
                self.infer(&env2, e2)?
            }
```

***Listing 6.4.** Inference for variables, abstractions, applications and both kinds of `let`. The other forms add equations in the same way. code/bachelor-3/06-type-systems/listings/infer.rs*

```text
# poly.lam -- five definitions, each generalised at its let
let id = \x. x in
let const = \x. \y. x in
let compose = \f. \g. \x. f (g x) in
let swap = \p. (snd p, fst p) in
letrec count = \n. if n == 0 then 0 else 1 + count (n - 1) in
swap (id true, compose (const 1) id false)
```

***Listing 6.5.** Five definitions with no type written. code/bachelor-3/06-type-systems/listings/poly.lam*

```
$ rustc --edition 2021 -O -o infer_demo infer_demo.rs && ./infer_demo poly.lam
id       : forall 'a. 'a -> 'a
const    : forall 'a 'b. 'a -> 'b -> 'a
compose  : forall 'a 'b 'c. ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
swap     : forall 'a 'b. 'a * 'b -> 'b * 'a
count    : int -> int
program  : int * bool
```

***Output 6.2.** The [principal type](#def-b3-type-systems-inference) of each definition of `poly.lam`, as inference generalises it, and of the program. The [type variables](#def-b3-type-systems-polymorphism) are renamed in order of appearance.*

**Theorem 6.14 (Principal types).**

If a closed expression of the $\lambda$-language has a type under the rules with [let-polymorphism](#def-b3-type-systems-polymorphism), algorithm W finds a [principal type](#def-b3-type-systems-inference) for it; otherwise W fails.

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

The proof goes by induction on the expression, with the unification theorem at each equation; it is longer than its idea, which is that W never makes a choice it did not have to make. [Output 6.3](#out-b3-type-systems-occurs) shows the two ways inference fails: an equation with no finite solution, caught by the occurs check, and a plain clash between two constructors.

```
$ rustc --edition 2021 -O -o occurs occurs.rs && ./occurs
\x. x x
    type error: 'a would have to equal 'a -> 'b, which contains it
\f. (\x. f (x x)) (\x. f (x x))
    type error: 'b would have to equal 'b -> 'c, which contains it
(\id. (id 1, id true)) (\x. x)
    type error: int is not bool
let id = \x. x in (id 1, id true)
    : int * bool
```

***Output 6.3.** Self-application and the combinator $Y$ fail the occurs check. A $\lambda$-bound identity used at two types is a clash; bound by `let`, the same identity is polymorphic.*

W is fast on the programs people write, but not in the worst case: a type can be far larger than the program that has it. The weekend problem builds a family of programs, each one line longer than the previous, whose types square in size at each line.

## 6.5 Propositions as types, and types that count

**You already know.**

In natural deduction, the introduction rule of $A \Rightarrow B$ derives it from a derivation of $B$ under the hypothesis $A$, and its elimination rule (modus ponens) derives $B$ from $A \Rightarrow B$ and $A$; $A \wedge B$ is introduced from $A$ and $B$, and eliminated to either (Year 2 volume).

Put rule abs beside the introduction of implication, with the expressions erased, and they are the same rule; app is modus ponens; the pair rules are the rules of conjunction. This is no coincidence.

**Definition 6.15 (Curry–Howard correspondence).**

The *Curry–Howard correspondence* pairs types with propositions and programs with proofs: in the simply typed $\lambda$-calculus, where every term terminates, a closed term of type $\tau$ is a proof of the proposition $\tau$ read with $\to$ as implication and $\times$ as conjunction, and reducing the term simplifies the proof.

![The correspondence, line by line. Read down the middle column, a type is a formula; read down the last, its proofs are the programs of that type.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-type-systems/fig-2dd9ec5c3d89.svg)

*The correspondence, line by line. Read down the middle column, a type is a formula; read down the last, its proofs are the programs of that type.*

The [principal type](#def-b3-type-systems-inference) of `swap` in [Output 6.2](#out-b3-type-systems-poly), $\alpha \times \beta \to \beta \times \alpha$, is the tautology $A \wedge B \Rightarrow B \wedge A$, and `swap` is its proof. Rust’s generics play the same game: a function generic in `A` and `B` cannot inspect values of those types, so its body can only rearrange what it is given, and a well-typed body that returns is a proof. The proviso matters: a body that loops for ever or calls `panic!` has every type, as does a recursive definition that never stops, so a language with general recursion, read as a logic, proves everything. The correspondence holds for the total, terminating fragment.

```rust
// curry_howard.rs -- three proofs in propositional logic, written as
// generic Rust functions: a type is a proposition, a value is a proof.

/// (A and B) implies (B and A)
fn swap<A, B>(p: (A, B)) -> (B, A) {
    (p.1, p.0)
}

/// From A implies B, and A, conclude B (modus ponens).
fn modus_ponens<A, B>(f: impl Fn(A) -> B, a: A) -> B {
    f(a)
}

/// (A implies B) and (B implies C) give (A implies C).
fn chain<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
    move |a| g(f(a))
}

fn main() {
    let proof = swap((1, "one"));
    let len_is_even = chain(|s: &str| s.len(), |n: usize| n % 2 == 0);
    println!("{proof:?} {} {}", modus_ponens(&len_is_even, "four"), len_is_even("odd"));
}
```

***Listing 6.6.** Three proofs as generic functions: commutativity of conjunction, modus ponens, and the transitivity of implication. code/bachelor-3/06-type-systems/listings/curry_howard.rs*

```
$ rustc --edition 2021 -O -o curry_howard curry_howard.rs && ./curry_howard
("one", 1) true false
```

***Output 6.4.** The proofs run: `swap` exchanges, and `chain` composes two functions into a third.*

**You already know.**

In Rust, assigning a non-`Copy` value or passing it by value moves it: the old variable can no longer be used. A borrow lends access without moving (Year 2 volume).

Types can track more than the shape of a value. Logic itself has systems in which a hypothesis must be used exactly once, and their programs are functions that use each argument once.

**Definition 6.16 (Linear type, affine type).**

A *linear* [type system](#def-b3-type-systems-type-system) requires every variable of certain types to be used exactly once; an *affine* one, at most once.

Rust’s ownership is [affine](#def-b3-type-systems-linear): a value of a type that is not `Copy` may be moved once, and a use after the move is a type error, reported before the program runs, exactly as a boolean added to an integer is. The borrow checker extends the idea with borrows, which use a value without consuming it, for a span of the program the checker computes.

```rust
// borrow_reject.rs -- a value used after it was moved: the borrow checker
// rejects the program, as a type checker rejects a type error.
// capture: exit
fn total(v: Vec<i32>) -> i32 {
    v.iter().sum()
}

fn main() {
    let v = vec![1, 2, 3];
    let t = total(v); // v is moved into total
    println!("{t} {}", v.len()); // used again: rejected
}
```

***Listing 6.7.** A vector moved into a function, then used again. code/bachelor-3/06-type-systems/listings/borrow_reject.rs*

```
$ rustc --edition 2021 -O -o borrow_reject borrow_reject.rs && ./borrow_reject
error[E0382]: borrow of moved value: `v`
  --> borrow_reject.rs:11:24
   |
 9 |     let v = vec![1, 2, 3];
   |         - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
10 |     let t = total(v); // v is moved into total
   |                   - value moved here
11 |     println!("{t} {}", v.len()); // used again: rejected
   |                        ^ value borrowed here after move
   |
```

***Output 6.5.** The compiler’s verdict: the use on line 11 needs the value moved on line 10. Like a type error, it names the two places involved. Some lines are left out.*

**In practice — Annotate the boundaries.**

Inference can type a whole program with no annotation, and the errors then appear far from their cause: a mistake in one function changes its inferred type, and the complaint comes from a caller. Programmers in languages with inference still write the types of top-level and exported functions. The annotation documents the interface, and it stops an error at the function that contains it.

**History — Principal types.**

Roger Hindley published the principal type-scheme of a term of combinatory logic in 1969. Robin Milner published a theory of type polymorphism in programming in 1978. In 1982 Luis Damas and Milner published their paper on [principal type](#def-b3-type-systems-inference) schemes for functional programs. The proof of safety by [progress](#def-b3-type-systems-safety) and [preservation](#def-b3-type-systems-safety), as in this chapter, follows a syntactic approach that Andrew Wright and Matthias Felleisen published in 1994.

## 6.6 Exercises

**Exercise 6.1 ★.**

Give the type of each term, or say why it has none: `\x: int. \y: bool. if y then x else 0`; `\f: int -> int. \x: int. f (f x)`; `(\x: bool. x) true`.

**Solution of Exercise 6.1.**

$\mathtt{int} \to \mathtt{bool} \to \mathtt{int}$; $(\mathtt{int} \to \mathtt{int}) \to \mathtt{int} \to \mathtt{int}$; $\mathtt{bool}$ (`exercise_1_types_of_terms`).

**Exercise 6.2 ★.**

Build the [typing derivation](#def-b3-type-systems-judgement) of `\x: int. \f: int -> bool. f x` and count its judgements.

**Solution of Exercise 6.2.**

Five judgements (`exercise_2_derivation`), written with the conclusion first:

| \|- \x: int. \f: int -> bool. f x : int -> (int -> bool) -> bool [abs] |
| --- | --- |
|   x: int \|- \f: int -> bool. f x : (int -> bool) -> bool [abs] |
|     x: int, f: int -> bool \|- f x : bool [app] |
|         x: int, f: int -> bool \|- f : int -> bool [var] |
|         x: int, f: int -> bool \|- x : int [var] |

**Exercise 6.3 ★.**

Which of these terms have a type? Give the [principal type](#def-b3-type-systems-inference) when there is one: `\x. x x`; `\f. \x. f x x`; `\p. fst p + snd p`; `\x. if x then x else 1`.

**Solution of Exercise 6.3.**

`\x. x x`: none, the occurs check fails on $\alpha \doteq \alpha \to \beta$. `\f. \x. f x x`: $(\alpha \to \alpha \to \beta) \to \alpha \to \beta$. `\p. fst p + snd p`: $\mathtt{int} \times \mathtt{int} \to \mathtt{int}$. `\x. if x then x else 1`: none; the condition makes $x$ a $\mathtt{bool}$, and the branches have types $\mathtt{bool}$ and $\mathtt{int}$ (`exercise_3_typable_or_not`).

**Exercise 6.4 ★.**

Predict the line that `infer_demo` would print for `let twice = \f. \x. f (f x) in …`.

**Solution of Exercise 6.4.**

`twice : forall 'a.\ ('a -> 'a) -> 'a -> 'a`: $f$ is applied to $x$ and to its own result, so its argument and result types are equal, and so is the type of $x$ (`exercise_4_twice`).

**Exercise 6.5 ★★.**

`exercises/ex5_noocc.rs` keeps a *triangular* substitution, whose bindings may mention other bound variables, and resolves a type by following them. With `occurs_check` false, inferring `\x. x x` accepts an equation and then never finishes printing the type. Which equation, and why does printing not end? Show that the occurs check fixes it, and explain why it cannot refuse a solvable problem.

**Solution of Exercise 6.5.**

$x$ gets $\alpha$, and the application $x\,x$ asks $\alpha \doteq \alpha \to \beta$. Without the check, the binding $\alpha := \alpha \to \beta$ is stored. Resolving $\alpha$ replaces it by $\alpha \to \beta$, whose $\alpha$ is replaced again, without end: the type it describes is infinite. The test gives the resolution a budget of 1,000 nodes and sees it exhausted; with the check, `unify` refuses the equation (`exercise_5_occurs_check`). The check never refuses a solvable problem: if $\alpha$ occurs in $\tau \ne \alpha$, then for any substitution $U$, $U(\alpha)$ is a proper subterm of $U(\tau)$, hence smaller, so $U(\alpha) \ne U(\tau)$.

**Exercise 6.6 ★★.**

The checker of [Listing 6.1](#lst-b3-type-systems-check) rejects pairs. Write the rules for $(e_1, e_2)$, `fst` and `snd`, and a typing function that has them; test it on `(\p: int * bool. if snd p then fst p else 0) (1, true)`.

**Solution of Exercise 6.6.**

$$
\begin{gather*}{\dfrac{\Gamma \vdash e_1 : \tau_1 \qquad  \Gamma \vdash e_2 : \tau_2}{\Gamma \vdash (e_1, e_2) : \tau_1 \times \tau_2}}

{\dfrac{\Gamma \vdash e : \tau_1 \times \tau_2}{\Gamma \vdash \mathtt{fst}\ e : \tau_1}}

{\dfrac{\Gamma \vdash e : \tau_1 \times \tau_2}{\Gamma \vdash \mathtt{snd}\ e : \tau_2}}\end{gather*}
$$

`exercises/ex6_pairs.rs` adds the three arms. The test types the example as $\mathtt{int}$, a pair holding a function as $\mathtt{int} \times (\mathtt{int} \to \mathtt{bool}) \to \mathtt{bool}$, and rejects `fst 3` (`exercise_6_pairs`).

**Exercise 6.7 ★★.**

Prove the substitution lemma ([Lemma 6.7](#lem-b3-type-systems-substitution)). You will need weakening: a judgement stays true when unused bindings are added to its context.

**Solution of Exercise 6.7.**

Weakening first: if $\Gamma \vdash e : \tau$, then $\Gamma, \Delta \vdash e : \tau$ for bindings $\Delta$ of variables not free in $e$, by induction on the derivation (each rule only looks up the free variables of $e$). Now induct on the derivation of $\Gamma, x : \sigma \vdash e : \tau$. If $e$ is $x$, then $\tau = \sigma$ and $e[x := v] = v$, and weakening of $\vdash v : \sigma$ gives $\Gamma \vdash v : \sigma$. If $e$ is another variable or a constant, the substitution changes nothing and the binding of $x$ was not used. If $e = \lambda y{:}\tau_1.\,e_0$, rename $y$ so that $y \ne x$ ($v$ is closed, so $y$ is not free in it); the premise is $\Gamma, x : \sigma, y : \tau_1 \vdash e_0 : \tau_2$, which is also derivable with the two bindings exchanged, since they concern different names; the induction hypothesis gives $\Gamma, y : \tau_1 \vdash e_0[x := v] : \tau_2$, and abs concludes. Application, `let`, `if`, the operators and pairs substitute into each premise, and the induction hypothesis applies to each.

**Exercise 6.8 ★★.**

Prove that in the simply typed core, with annotated parameters, a term has at most one type in a given context. Does this hold for the unannotated calculus?

**Solution of Exercise 6.8.**

By induction on the term. A variable has the type of its last binding in the context, a constant its one type. For $\lambda x{:}\tau_1.\,e$, the annotation fixes $\tau_1$ and the induction hypothesis fixes the type of $e$ in the extended context, hence the arrow. For $e_1\,e_2$, the hypothesis fixes $e_1$’s type, which must be some $\tau_1 \to \tau_2$, and the result is that $\tau_2$. The other forms are alike: each has one rule, whose conclusion is determined by the types of the premises. Without annotations it fails at once: `\x. x` has the types $\mathtt{int} \to \mathtt{int}$, $\mathtt{bool} \to \mathtt{bool}$, and every other $\tau \to \tau$. This is why the unannotated calculus needs [principal types](#def-b3-type-systems-inference).

**Exercise 6.9 ★★.**

Why is `let id = \x. x in id id` typable, and what is its [principal type](#def-b3-type-systems-inference), while `(\id. id id) (\x. x)` is not?

**Solution of Exercise 6.9.**

Bound by `let`, $\mathit{id}$ has the scheme $\forall \alpha.\,\alpha \to \alpha$, and each use takes a fresh instance: the function position $(\beta \to \beta) \to (\beta \to \beta)$, the argument $\beta \to \beta$. The result is $\beta \to \beta$, printed `'a -> 'a`. Bound by $\lambda$, $\mathit{id}$ has one type $\tau$ throughout the body, and $\mathit{id}\,\mathit{id}$ requires $\tau \doteq \tau \to \tau'$, which the occurs check refuses (`exercise_9_self_application`).

**Exercise 6.10 ★★★.**

Give a [typing rule](#def-b3-type-systems-judgement) for `letrec f = \x. e1 in e2` without polymorphism, and prove the case of [preservation](#def-b3-type-systems-safety) for the step that unfolds it.

**Solution of Exercise 6.10.**

$$
\begin{gather*}{\dfrac{\Gamma, f : \tau_1 \to \tau_2, x : \tau_1 \vdash e_1 : \tau_2 \qquad  \Gamma, f : \tau_1 \to \tau_2 \vdash e_2 : \tau}{\Gamma \vdash \mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_2 : \tau}}\end{gather*}
$$

The step gives $e_2[f := u]$ with $u = \lambda x.\,\mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_1$. By the substitution lemma applied to the second premise, it suffices that $\vdash u : \tau_1 \to \tau_2$. By abs , that is $x : \tau_1 \vdash \mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_1 : \tau_2$, and by the rule itself it needs $x : \tau_1, f : \tau_1 \to \tau_2, x : \tau_1 \vdash e_1 : \tau_2$ and $x : \tau_1, f : \tau_1 \to \tau_2 \vdash e_1 : \tau_2$. The first premise of the original rule, with $\Gamma$ empty since the program is closed, gives both: the outer binding of $x$ is hidden by the inner one in the first, and the second is the same context in another order.

**Exercise 6.11 ★★★.**

Show that [let-polymorphism](#def-b3-type-systems-polymorphism) is needed: give a program that `Infer` types, and that the same inference with `generalise` set to false rejects; explain exactly which equation fails, and say why generalising at `let` is sound, given the semantics of `let`.

**Solution of Exercise 6.11.**

`let id = \x. x in (id 1, id true)`. Without generalisation, $\mathit{id}$ keeps the type $\alpha \to \alpha$ with $\alpha$ a variable shared by both uses; `id 1` solves $\alpha = \mathtt{int}$, and `id true` then asks $\mathtt{int} \doteq \mathtt{bool}$, a clash. With generalisation, each use instantiates its own copy (`exercise_11_let_polymorphism_is_needed`). It is sound because `let x = e1 in e2` evaluates $e_1$ to a value $v$ and continues with $e_2[x := v]$: each occurrence of $x$ becomes its own copy of $v$, and since the generalised variables do not occur in $\Gamma$, the derivation of $v$’s type can be redone with any types put in their place, one instance per copy.

**Exercise 6.12 ★★★.**

Add references to the language: `ref e` creates a cell, `!r` reads it, `r := e` writes it, with type $\tau\ \mathtt{ref}$ for a cell holding a $\tau$. Show that generalising `let r = ref (\x. x) in …` lets a well-typed program apply a function of type $\mathtt{int} \to \mathtt{int}$ to a boolean. State the *value restriction*, which generalises `let x = e` only when $e$ is a value, and explain why it is [safe](#def-b3-type-systems-safety) and why it still types the programs of [Listing 6.5](#lst-b3-type-systems-poly).

**Solution of Exercise 6.12.**

Take the program

`let r = ref (\x. x) in (r := (\n. n + 1); (!r) true)`

Generalising gives $r : \forall \alpha.\,(\alpha \to \alpha)\ \mathtt{ref}$; the assignment uses the instance $\alpha = \mathtt{int}$, the read the instance $\alpha = \mathtt{bool}$, and the program is typed. But there is one cell, not one per use: after the assignment it holds $\lambda n.\,n + 1$, and the program computes $\mathtt{true} + 1$, stuck. The argument of exercise [6.11](#exo-b3-type-systems-11) broke because evaluating $e_1$ allocated a cell that all the copies share. The *value restriction* generalises `let x = e1 in e2` only when $e_1$ is a value. Evaluating a value does nothing, so copies of it share nothing, and the argument of exercise [6.11](#exo-b3-type-systems-11) applies again. `ref (\x. x)` is an application, not a value, so $r$ keeps a single [type variable](#def-b3-type-systems-polymorphism), and the program is rejected with a clash between $\mathtt{int}$ and $\mathtt{bool}$. Every definition of [Listing 6.5](#lst-b3-type-systems-poly) is an abstraction, a value, so all are still generalised.

## 6.7 Weekend problem

**Problem 6.1.**

Weekend problem — Types that explode

The program `let f0 = \x. (x, x) in let f1 = \x. f0 (f0 x) in ... in fn` defines $n + 1$ functions, each applying the previous one twice. `blowup.rs` builds it for $n = 0, \dots, 4$, infers its [principal type](#def-b3-type-systems-inference) $\texttt{\textquotesingle a} \to T_n$, and measures $T_n$ two ways: as a tree, by its leaves, and as a graph in which equal subtrees are drawn once.

```
$ rustc --edition 2021 -O -o blowup blowup.rs && ./blowup
 n  program  unify calls  leaves of the type  distinct subtrees
 0       25            0                   2                  2
 1       51            6                   4                  3
 2       77           12                  16                  5
 3      103           18                 256                  9
 4      129           24               65536                 17
```

***Output 6.6.** For each $n$: the program’s length in characters, the calls to `unify`, the leaves of $T_n$, and its distinct subtrees.*

**Part I — By hand.**

1. Infer the [principal type](#def-b3-type-systems-inference) of `\x. (x, x)` , writing every equation.
2. Infer the type of `let f0 = \x. (x, x) in \x. f0 (f0 x)` . Where are the two instances of $f_0$ ’s scheme used?
3. What is the type of `f0 (f0 1)` ?
4. Why is `(\f0. \x. f0 (f0 x)) (\x. (x, x))` rejected? Write the equation that fails.
5. Write $T_1$ and $T_2$ .
6. How does the program’s length grow with $n$ ?

**Part II — The family.**

7. Show that $T_k = T_{k-1}[\texttt{\textquotesingle a} := T_{k-1}]$ for $k \ge 1$ , with $T_0 = \texttt{\textquotesingle a} \times \texttt{\textquotesingle a}$ .
8. Deduce the number of leaves $\ell_k$ of $T_k$ : give a recurrence, then a closed form.
9. Give the depth of $T_k$ .
10. Count the distinct subtrees of $T_k$ , and explain the column of [Output 6.6](#out-b3-type-systems-blowup) .
11. Check the three formulas against the table.
12. What would the row $n = 5$ say? Why does the program not print it?

**Part III — Where the time goes.**

13. The unify calls grow by 6 per line. Which equations does each `let` line contribute?
14. If unification is called so few times, where does the work of inference go when types are trees?
15. Estimate the memory for $T_5$ as a tree, at 16 bytes per node.
16. With types as graphs (each subtree shared), what is the size of $T_n$ ? Is inference then polynomial in the program’s length?
17. Printing $T_n$ costs its number of leaves at least. What does this say of any algorithm that outputs [principal types](#def-b3-type-systems-inference) as text?
18. Harry Mairson showed in 1990 that deciding whether an ML program has a type is complete for deterministic exponential time. What does this add to the observation of the previous question?

**Part IV — Why it does not happen.**

19. Which feature of the family produces the growth: the pairs, the nesting of `let` , or the doubling? Remove each in turn and say what remains.
20. Real programs nest `let` s deeply. Why do their types stay small?
21. What does a type annotation on `f1` change for the checker’s work?
22. Would the explosion happen in the simply typed core, where each parameter carries its type? Where would the size go?
23. What does a compiler with inference do to keep its error messages readable when a type is large?
24. Sum up: give the size of $T_n$ as a tree and as a graph, and the cost of inference on this family in terms of the program’s length.

**Solution of Problem 6.1.**

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

**1.** $x : \alpha$; the pair has type $\alpha \times \alpha$; the abstraction $\alpha \to \alpha \times \alpha$. There is no application, so no equation at all.

**2.** $f_0 : \forall \alpha.\,\alpha \to \alpha \times \alpha$. With $x : \beta$, the inner use is instantiated as $\gamma \to \gamma \times \gamma$, and $\gamma \to \gamma \times \gamma \doteq \beta \to \delta$ gives $\gamma = \beta$, $\delta = \beta \times \beta$. The outer use is instantiated afresh, $\epsilon \to \epsilon \times \epsilon$, and unifying with $\beta \times \beta \to \zeta$ gives $\epsilon = \beta \times \beta$. The type is $\beta \to (\beta \times \beta) \times (\beta \times \beta)$: the two instances are at $\beta$ and at $\beta \times \beta$.

**3.** $(\mathtt{int} \times \mathtt{int}) \times (\mathtt{int} \times \mathtt{int})$.

**4.** $f_0$ is a parameter, with one type. Its two uses force argument and result types to be equal, so $f_0 : \alpha \to \alpha$, and the argument then asks $\alpha \to \alpha \doteq \beta \to \beta \times \beta$, that is $\beta \doteq \beta \times \beta$, which the occurs check refuses.

**5.** $T_1 = (\texttt{\textquotesingle a} \times \texttt{\textquotesingle a}) \times (\texttt{\textquotesingle a} \times \texttt{\textquotesingle a})$; $T_2 = (T_1 \times T_1) \times (T_1 \times T_1)$ with each $\texttt{\textquotesingle a}$ of $T_1$ replaced by $T_1$, that is $T_1[\texttt{\textquotesingle a} := T_1]$: 16 leaves.

**6.** $25 + 26n$ characters: linearly.

**7.** With $x : \beta$, the inner use of $f_{k-1}$ gives $T_{k-1}[\texttt{\textquotesingle a} := \beta]$, and the outer use is an instance applied to that, so its result is $T_{k-1}[\texttt{\textquotesingle a} := T_{k-1}[\texttt{\textquotesingle a} := \beta]]$; up to the name of $\beta$, $T_k = T_{k-1}[\texttt{\textquotesingle a} := T_{k-1}]$.

**8.** Each of the $\ell_{k-1}$ leaves of $T_{k-1}$ is replaced by a copy of $T_{k-1}$: $\ell_k = \ell_{k-1}^2$, $\ell_0 = 2$, so $\ell_k = 2^{2^k}$.

**9.** The depth doubles: $d_k = 2d_{k-1}$, $d_0 = 1$, so $d_k = 2^k$.

**10.** $T_k$ is a complete binary tree of products, all of whose leaves are $\texttt{\textquotesingle a}$, so all its subtrees at the same depth are equal. There is one distinct subtree per depth, from the root to the leaves: $2^k + 1$.

**11.** Leaves 2, 4, 16, 256, 65,536 are $2^{2^n}$; distinct subtrees 2, 3, 5, 9, 17 are $2^n + 1$; lengths 25, 51, 77, 103, 129 are $25 + 26n$.

**12.** Length 155, 30 unify calls, $2^{32} = 4{,}294{,}967{,}296$ leaves, 33 distinct subtrees. The tree has more than eight billion nodes and does not fit in the laptop’s memory.

**13.** Each line $\lambda x.\,f_{k-1}\,(f_{k-1}\,x)$ has two applications; each unifies an instance of an arrow with $\tau \to \beta$, which is one call for the two arrows and two recursive calls for their children: 6 calls per line, and none for $f_0$.

**14.** Into building and copying types: each instantiation copies the scheme’s type, and each application of the substitution rebuilds the type it is applied to, at a cost proportional to its size as a tree, $2^{2^k}$ leaves at line $k$.

**15.** A tree with $2^{32}$ leaves has $2^{33} - 1$ nodes, about $8.6 \times 10^9$, so about 137 GB.

**16.** $2^n + 1$ nodes. Inference with shared types does work proportional to that size at each line, which is exponential in $n$, hence in the program’s length: still not polynomial.

**17.** Writing $T_n$ out as text takes at least $2^{2^n}$ symbols, doubly exponential in the program’s length, so no algorithm that prints [principal types](#def-b3-type-systems-inference) in full can be faster on this family.

**18.** That even the yes-or-no question, with no type to print, needs exponential time in the worst case: the cost is not an artefact of the output’s size, and no representation makes typability polynomial, since the time hierarchy theorem separates polynomial from exponential time.

**19.** All three are needed. Without pairs, $f_0 = \lambda x.\,x$ and every $T_k$ is $\texttt{\textquotesingle a}$. Without the doubling, $f_k = \lambda x.\,f_{k-1}\,x$ and $T_k = T_0$. Without `let` (parameters instead), the family is rejected, question 4: polymorphism is what lets $f_{k-1}$ be used at two types.

**20.** Each definition is used at instances whose size the programmer has in mind, and chains in which every function squares the type of the previous one do not occur in code people write and read.

**21.** The checker compares the inferred type with the annotation instead of propagating a free variable, but the annotation itself is $\texttt{\textquotesingle a} \to T_1$: annotating $f_n$ means writing a type of $2^{2^n}$ leaves, so the cost moves into the program.

**22.** No polymorphism means one copy of each $f_{k-1}$ per type it is used at, with its parameter’s type written out: the program itself would have to grow, doubly exponentially in its annotations, to compute the same thing.

**23.** It names large types, prints them with sharing or elides their middle, and shows the smallest part that disagrees rather than the whole type.

**24.** As a tree $T_n$ has $2^{2^n}$ leaves; as a graph $2^n + 1$ nodes. With trees, inference on this family takes time doubly exponential in the program’s length; with sharing, exponential.
