Informatique · Livre 5 · Licence 3

University Computer Science — Year 3

Ce livre n’est pas encore disponible en Français. Éditions : English.

University Computer Science — Year 3 · Licence 3

6Type Systems and Type Inference

Chapter 4 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: 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 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:τx : \tau of variables to types; a later binding of a name hides an earlier one. A typing judgement Γ⊢e:τ\Gamma \vdash e : \tau asserts that in the context Γ\Gamma, the expression ee 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 τ::=int∣bool∣τ→τ∣τ×τ\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.

(x:τ)∈ΓΓ⊢x:τ  varΓ,x:τ1⊢e:τ2Γ⊢λx:τ1. e:τ1→τ2  absΓ⊢e1:τ1→τ2Γ⊢e2:τ1Γ⊢e1 e2:τ2  appΓ⊢e1:τ1Γ,x:τ1⊢e2:τ2Γ⊢let x=e1 in e2:τ2  letΓ⊢e1:boolΓ⊢e2:τΓ⊢e3:τΓ⊢if e1 then e2 else e3:τ  ifΓ⊢e1:intΓ⊢e2:intΓ⊢e1+e2:int  op\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). Recording the rule and the premises at each node builds the derivation itself.

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 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 for the argument is the figure below.

 x:int⊢x:int var x:int⊢2:intx:int⊢x×2:int op⊢λx:int. x×2:int→int abs\begin{gather*}{\dfrac{{\dfrac{{\dfrac{\ }{x : \mathtt{int} \vdash x : \mathtt{int}}\,\scriptstyle\text{var}} \qquad {\dfrac{\ }{x : \mathtt{int} \vdash 2 : \mathtt{int}}}}{x : \mathtt{int} \vdash x \times 2 : \mathtt{int}}\,\scriptstyle\text{op}}}{\vdash \lambda x{:}\mathtt{int}.\,x \times 2 : \mathtt{int} \to \mathtt{int}}\,\scriptstyle\text{abs}}\end{gather*}
Four judgements, the last four lines of Output 6.1, 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 is only worth its rules if they guarantee something. The guarantee is stated against the small-step semantics of chapter 5.

Definition 6.4 (Type safety, progress, preservation)

A 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 ⊢e:τ\vdash e : \tau and e→e′e \to e', then ⊢e′:τ\vdash e' : \tau. The canonical forms of a type are the shapes of its closed values.

Lemma 6.5 (Canonical forms)

If vv is a value and ⊢v:τ\vdash v : \tau, then: if τ=int\tau = \mathtt{int}, vv is an integer; if τ=bool\tau = \mathtt{bool}, vv is true\mathtt{true} or false\mathtt{false}; if τ=τ1→τ2\tau = \tau_1 \to \tau_2, vv is an abstraction; if τ=τ1×τ2\tau = \tau_1 \times \tau_2, vv 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 int\mathtt{int} or bool\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 ⊢e:τ\vdash e : \tau, then ee is a value or there is e′e' with e→e′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 e1 e2e_1\,e_2, typed by app with ⊢e1:τ1→τ2\vdash e_1 : \tau_1 \to \tau_2 and ⊢e2:τ1\vdash e_2 : \tau_1. By induction, e1e_1 is a value or steps; if it steps, so does e1 e2e_1\,e_2 by the first congruence rule. Otherwise, if e2e_2 steps, e1 e2e_1\,e_2 does by the second. Otherwise both are values, and by canonical forms e1e_1 is an abstraction λx. e\lambda x.\,e, so e1 e2e_1\,e_2 is a redex and steps to e[x:=e2]e[x := e_2]. For if\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 of the shapes the computing rule needs. ∎

Preservation needs one lemma: substituting a value of the right type for a variable keeps the type.

Lemma 6.7 (Substitution)

If Γ,x:σ⊢e:τ\Gamma, x : \sigma \vdash e : \tau and ⊢v:σ\vdash v : \sigma, then Γ⊢e[x:=v]:τ\Gamma \vdash e[x := v] : \tau.

The proof is a short induction on the derivation of ee’s type (exercise 6.7).

Theorem 6.8 (Preservation)

If ⊢e:τ\vdash e : \tau and e→e′e \to e', then ⊢e′:τ\vdash e' : \tau.

Proof. By induction on the derivation of e→e′e \to e'. For the β\beta-rule, (λx. e0) v→e0[x:=v](\lambda x.\,e_0)\,v \to e_0[x := v]: the typing of the redex ends with app, above which abs gives x:τ1⊢e0:τx : \tau_1 \vdash e_0 : \tau, and the argument has ⊢v:τ1\vdash v : \tau_1; the substitution lemma gives ⊢e0[x:=v]:τ\vdash e_0[x := v] : \tau. A let is the same. For if true then e2 else e3→e2\mathtt{if}\ \mathtt{true}\ \mathtt{then}\ e_2\ \mathtt{else}\ e_3 \to e_2, rule if types e2e_2 with τ\tau. For 2+3→52 + 3 \to 5, both sides are integers. For a congruence step, such as e1 e2→e1′ e2e_1\,e_2 \to e_1'\,e_2, the induction hypothesis gives e1′e_1' the type of e1e_1, and app applies again. The case of letrec is exercise 6.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 keeps every term reached well-typed, and progress 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.
Progress gives each well-typed term a next step unless it is a value; preservation 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 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, λx:int. x\lambda x{:}\mathtt{int}.\,x and λx:bool. x\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 ∀α1…αn. τ\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 let id=λx. x in (id 1,id true)\mathtt{let}\ \mathit{id} = \lambda x.\,x\ \mathtt{in}\ (\mathit{id}\ 1, \mathit{id}\ \mathtt{true}) is well typed: id\mathit{id} gets ∀α. α→α\forall \alpha.\,\alpha \to \alpha, and its two uses take the instances int→int\mathtt{int} \to \mathtt{int} and bool→bool\mathtt{bool} \to \mathtt{bool}. The same program with id\mathit{id} bound by a λ\lambda, (λid. (id 1,id true)) (λx. x)(\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:

(x:∀α⃗. τ)∈ΓΓ⊢x:τ[α⃗:=τ⃗]  instΓ⊢e1:τ1Γ,x:∀α⃗. τ1⊢e2:τ2α⃗ not free in ΓΓ⊢let x=e1 in e2:τ2  let\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 λx. x x\lambda x.\,x\,x, the variable xx 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 to types and applies to a type by replacing each of its variables. A type equation τ1≐τ2\tau_1 \doteq \tau_2 asks for a type substitution SS with S(τ1)=S(τ2)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 keeps the substitution idempotent: when α:=τ\alpha := \tau is added, τ\tau is substituted into every binding already present, so applying the substitution once is enough.

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).
Unifying (’ a→’ b)×’ a(\texttt{\textquotesingle a} \to \texttt{\textquotesingle b}) \times \texttt{\textquotesingle a} with (int→bool)×’ c(\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 τ1\tau_1 and τ2\tau_2 have a unifier, unify returns a most general one; otherwise it fails.

Proof. We prove: if unify is called with a substitution SS, and UU is any unifier of S(τ1)S(\tau_1) and S(τ2)S(\tau_2) that is an instance of SS (U=R∘SU = R \circ S for some RR), then unify succeeds with an S′S' of which UU is still an instance, and S′S' unifies the two types. The induction is on the number of variables not bound by SS, then on the size of the types. Write a=S(τ1)a = S(\tau_1), b=S(τ2)b = S(\tau_2). If aa is a variable α\alpha and b≠αb \ne \alpha, then U(α)=U(b)U(\alpha) = U(b); were α\alpha to occur in bb, U(b)U(b) would contain U(α)U(\alpha) as a proper subterm, so it could not equal it: the occurs check fails only when there is no unifier. Otherwise S′={α:=b}∘SS' = \{\alpha := b\} \circ S unifies, and UU is an instance of it, since UU already sends α\alpha to U(b)U(b). If both are arrows a1→a2a_1 \to a_2 and b1→b2b_1 \to b_2, then UU unifies a1a_1 with b1b_1 and a2a_2 with b2b_2; the first recursive call gives S1S_1 of which UU is an instance, and the second call, on smaller types or with fewer unbound variables, gives S′S'. If the two have different constructors, no substitution can make them equal. Taking SS 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. An application e1 e2e_1\,e_2 infers τ1\tau_1 and τ2\tau_2, takes a fresh β\beta and unifies τ1\tau_1 with τ2→β\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.

    /// 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
    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
# 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 of each definition of poly.lam, as inference generalises it, and of the program. The type variables 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, algorithm W finds a principal type 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 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 YY 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⇒BA \Rightarrow B derives it from a derivation of BB under the hypothesis AA, and its elimination rule (modus ponens) derives BB from A⇒BA \Rightarrow B and AA; A∧BA \wedge B is introduced from AA and BB, 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.
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 of swap in Output 6.2, α×β→β×α\alpha \times \beta \to \beta \times \alpha, is the tautology A∧B⇒B∧AA \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.

// 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 requires every variable of certain types to be used exactly once; an affine one, at most once.

Rust’s ownership is affine: 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.

// 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 schemes for functional programs. The proof of safety by progress and preservation, 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

Solution of Exercise 6.1.

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

Exercise 6.2 ★

Build the typing derivation of \x: int. \f: int -> bool. f x and count its judgements.

Solution

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 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

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: int×int→int\mathtt{int} \times \mathtt{int} \to \mathtt{int}. \x. if x then x else 1: none; the condition makes xx a bool\mathtt{bool}, and the branches have types bool\mathtt{bool} and int\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

Solution of Exercise 6.4.

twice : forall 'a.\ ('a -> 'a) -> 'a -> 'a: ff is applied to xx and to its own result, so its argument and result types are equal, and so is the type of xx (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

Solution of Exercise 6.5.

xx gets α\alpha, and the application x xx\,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 UU, U(α)U(\alpha) is a proper subterm of U(τ)U(\tau), hence smaller, so U(α)≠U(τ)U(\alpha) \ne U(\tau).

Exercise 6.6 ★★

The checker of Listing 6.1 rejects pairs. Write the rules for (e1,e2)(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

Solution of Exercise 6.6.

Γ⊢e1:τ1Γ⊢e2:τ2Γ⊢(e1,e2):τ1×τ2Γ⊢e:τ1×τ2Γ⊢fst e:τ1Γ⊢e:τ1×τ2Γ⊢snd e:τ2\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 int\mathtt{int}, a pair holding a function as int×(int→bool)→bool\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). You will need weakening: a judgement stays true when unused bindings are added to its context.

Solution

Solution of Exercise 6.7.

Weakening first: if Γ⊢e:τ\Gamma \vdash e : \tau, then Γ,Δ⊢e:τ\Gamma, \Delta \vdash e : \tau for bindings Δ\Delta of variables not free in ee, by induction on the derivation (each rule only looks up the free variables of ee). Now induct on the derivation of Γ,x:σ⊢e:τ\Gamma, x : \sigma \vdash e : \tau. If ee is xx, then τ=σ\tau = \sigma and e[x:=v]=ve[x := v] = v, and weakening of ⊢v:σ\vdash v : \sigma gives Γ⊢v:σ\Gamma \vdash v : \sigma. If ee is another variable or a constant, the substitution changes nothing and the binding of xx was not used. If e=λy:τ1. e0e = \lambda y{:}\tau_1.\,e_0, rename yy so that y≠xy \ne x (vv is closed, so yy is not free in it); the premise is Γ,x:σ,y:τ1⊢e0:τ2\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 Γ,y:τ1⊢e0[x:=v]:τ2\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

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 λx:τ1. e\lambda x{:}\tau_1.\,e, the annotation fixes τ1\tau_1 and the induction hypothesis fixes the type of ee in the extended context, hence the arrow. For e1 e2e_1\,e_2, the hypothesis fixes e1e_1’s type, which must be some τ1→τ2\tau_1 \to \tau_2, and the result is that τ2\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 int→int\mathtt{int} \to \mathtt{int}, bool→bool\mathtt{bool} \to \mathtt{bool}, and every other τ→τ\tau \to \tau. This is why the unannotated calculus needs principal types.

Exercise 6.9 ★★

Why is let id = \x. x in id id typable, and what is its principal type, while (\id. id id) (\x. x) is not?

Solution

Solution of Exercise 6.9.

Bound by let, id\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, id\mathit{id} has one type τ\tau throughout the body, and id id\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 for letrec f = \x. e1 in e2 without polymorphism, and prove the case of preservation for the step that unfolds it.

Solution

Solution of Exercise 6.10.

Γ,f:τ1→τ2,x:τ1⊢e1:τ2Γ,f:τ1→τ2⊢e2:τΓ⊢letrec f=λx. e1 in e2:τ\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 e2[f:=u]e_2[f := u] with u=λx. letrec f=λx. e1 in e1u = \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 ⊢u:τ1→τ2\vdash u : \tau_1 \to \tau_2. By abs, that is x:τ1⊢letrec f=λx. e1 in e1:τ2x : \tau_1 \vdash \mathtt{letrec}\ f = \lambda x.\,e_1\ \mathtt{in}\ e_1 : \tau_2, and by the rule itself it needs x:τ1,f:τ1→τ2,x:τ1⊢e1:τ2x : \tau_1, f : \tau_1 \to \tau_2, x : \tau_1 \vdash e_1 : \tau_2 and x:τ1,f:τ1→τ2⊢e1:τ2x : \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 xx 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 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

Solution of Exercise 6.11.

let id = \x. x in (id 1, id true). Without generalisation, id\mathit{id} keeps the type α→α\alpha \to \alpha with α\alpha a variable shared by both uses; id 1 solves α=int\alpha = \mathtt{int}, and id true then asks int≐bool\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 e1e_1 to a value vv and continues with e2[x:=v]e_2[x := v]: each occurrence of xx becomes its own copy of vv, and since the generalised variables do not occur in Γ\Gamma, the derivation of vv’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 τ ref\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 int→int\mathtt{int} \to \mathtt{int} to a boolean. State the value restriction, which generalises let x = e only when ee is a value, and explain why it is safe and why it still types the programs of Listing 6.5.

Solution

Solution of Exercise 6.12.

Take the program

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

Generalising gives r:∀α. (α→α) refr : \forall \alpha.\,(\alpha \to \alpha)\ \mathtt{ref}; the assignment uses the instance α=int\alpha = \mathtt{int}, the read the instance α=bool\alpha = \mathtt{bool}, and the program is typed. But there is one cell, not one per use: after the assignment it holds λn. n+1\lambda n.\,n + 1, and the program computes true+1\mathtt{true} + 1, stuck. The argument of exercise 6.11 broke because evaluating e1e_1 allocated a cell that all the copies share. The value restriction generalises let x = e1 in e2 only when e1e_1 is a value. Evaluating a value does nothing, so copies of it share nothing, and the argument of exercise 6.11 applies again. ref (\x. x) is an application, not a value, so rr keeps a single type variable, and the program is rejected with a clash between int\mathtt{int} and bool\mathtt{bool}. Every definition of Listing 6.5 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+1n + 1 functions, each applying the previous one twice. blowup.rs builds it for n=0,…,4n = 0, \dots, 4, infers its principal type ’ a→Tn\texttt{\textquotesingle a} \to T_n, and measures TnT_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 nn: the program’s length in characters, the calls to unify, the leaves of TnT_n, and its distinct subtrees.

Part I — By hand.

  1. Infer the principal type 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 f0f_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 T1T_1 and T2T_2.
  6. How does the program’s length grow with nn?

Part II — The family.

  1. Show that Tk=Tk−1[’ a:=Tk−1]T_k = T_{k-1}[\texttt{\textquotesingle a} := T_{k-1}] for k≥1k \ge 1, with T0=’ a×’ aT_0 = \texttt{\textquotesingle a} \times \texttt{\textquotesingle a}.
  2. Deduce the number of leaves ℓk\ell_k of TkT_k: give a recurrence, then a closed form.
  3. Give the depth of TkT_k.
  4. Count the distinct subtrees of TkT_k, and explain the column of Output 6.6.
  5. Check the three formulas against the table.
  6. What would the row n=5n = 5 say? Why does the program not print it?

Part III — Where the time goes.

  1. The unify calls grow by 6 per line. Which equations does each let line contribute?
  2. If unification is called so few times, where does the work of inference go when types are trees?
  3. Estimate the memory for T5T_5 as a tree, at 16 bytes per node.
  4. With types as graphs (each subtree shared), what is the size of TnT_n? Is inference then polynomial in the program’s length?
  5. Printing TnT_n costs its number of leaves at least. What does this say of any algorithm that outputs principal types as text?
  6. 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.

  1. 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.
  2. Real programs nest lets deeply. Why do their types stay small?
  3. What does a type annotation on f1 change for the checker’s work?
  4. Would the explosion happen in the simply typed core, where each parameter carries its type? Where would the size go?
  5. What does a compiler with inference do to keep its error messages readable when a type is large?
  6. Sum up: give the size of TnT_n as a tree and as a graph, and the cost of inference on this family in terms of the program’s length.
Solution

Solution of Problem 6.1.

The formulas are asserted in tests/pb_test.rs.

1. x:α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. f0:∀α. α→α×αf_0 : \forall \alpha.\,\alpha \to \alpha \times \alpha. With x:β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. (int×int)×(int×int)(\mathtt{int} \times \mathtt{int}) \times (\mathtt{int} \times \mathtt{int}).

4. f0f_0 is a parameter, with one type. Its two uses force argument and result types to be equal, so f0:α→α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. T1=(’ a×’ a)×(’ a×’ a)T_1 = (\texttt{\textquotesingle a} \times \texttt{\textquotesingle a}) \times (\texttt{\textquotesingle a} \times \texttt{\textquotesingle a}); T2=(T1×T1)×(T1×T1)T_2 = (T_1 \times T_1) \times (T_1 \times T_1) with each ’ a\texttt{\textquotesingle a} of T1T_1 replaced by T1T_1, that is T1[’ a:=T1]T_1[\texttt{\textquotesingle a} := T_1]: 16 leaves.

6. 25+26n25 + 26n characters: linearly.

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

8. Each of the ℓk−1\ell_{k-1} leaves of Tk−1T_{k-1} is replaced by a copy of Tk−1T_{k-1}: ℓk=ℓk−12\ell_k = \ell_{k-1}^2, ℓ0=2\ell_0 = 2, so ℓk=22k\ell_k = 2^{2^k}.

9. The depth doubles: dk=2dk−1d_k = 2d_{k-1}, d0=1d_0 = 1, so dk=2kd_k = 2^k.

10. TkT_k is a complete binary tree of products, all of whose leaves are ’ a\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: 2k+12^k + 1.

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

12. Length 155, 30 unify calls, 232=4,294,967,2962^{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 λx. fk−1 (fk−1 x)\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 f0f_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, 22k2^{2^k} leaves at line kk.

15. A tree with 2322^{32} leaves has 233−12^{33} - 1 nodes, about 8.6×1098.6 \times 10^9, so about 137 GB.

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

17. Writing TnT_n out as text takes at least 22n2^{2^n} symbols, doubly exponential in the program’s length, so no algorithm that prints principal types 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, f0=λx. xf_0 = \lambda x.\,x and every TkT_k is ’ a\texttt{\textquotesingle a}. Without the doubling, fk=λx. fk−1 xf_k = \lambda x.\,f_{k-1}\,x and Tk=T0T_k = T_0. Without let (parameters instead), the family is rejected, question 4: polymorphism is what lets fk−1f_{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 ’ a→T1\texttt{\textquotesingle a} \to T_1: annotating fnf_n means writing a type of 22n2^{2^n} leaves, so the cost moves into the program.

22. No polymorphism means one copy of each fk−1f_{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 TnT_n has 22n2^{2^n} leaves; as a graph 2n+12^n + 1 nodes. With trees, inference on this family takes time doubly exponential in the program’s length; with sharing, exponential.

Termes définis dans ce chapitre

Voir les 1050 termes du glossaire