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 -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 is a finite list of bindings of variables to types; a later binding of a name hides an earlier one. A typing judgement asserts that in the context , the expression has type . 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 -language are , the arrow associating to the right. Here are the rules for its core.
Integer and boolean constants have their obvious types; and 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 -calculus)
The simply typed -calculus is the -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))),
}
}
$ 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
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.
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 and , then . The canonical forms of a type are the shapes of its closed values.
Lemma 6.5 (Canonical forms)
If is a value and , then: if , is an integer; if , is or ; if , is an abstraction; if , 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 or , 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 , then is a value or there is with .
Proof. By induction on the derivation. A variable cannot be typed in the empty context, and constants and abstractions are values. Consider , typed by app with and . By induction, is a value or steps; if it steps, so does by the first congruence rule. Otherwise, if steps, does by the second. Otherwise both are values, and by canonical forms is an abstraction , so is a redex and steps to . For , , 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 and , then .
The proof is a short induction on the derivation of ’s type (exercise 6.7).
Theorem 6.8 (Preservation)
If and , then .
Proof. By induction on the derivation of . For the -rule, : the typing of the redex ends with app, above which abs gives , and the argument has ; the substitution lemma gives . A let is the same. For , rule if types with . For , both sides are integers. For a congruence step, such as , the induction hypothesis gives the type of , 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. ∎
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, and are two functions. One would like to write the identity once.
Definition 6.10 (Type variable, type scheme, parametric polymorphism)
A type variable stands for an unknown type; we print them 'a, 'b, …. A type scheme 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 .
So is well typed: gets , and its two uses take the instances and . The same program with bound by a , , is rejected: a parameter has one type in the whole body. Two rules express this:
The side condition matters: a variable that also occurs in the type of something in is not free to vary, since that thing fixes it.
The restriction to let is what keeps inference decidable: a system where a -bound variable could be used at two types needs annotations. And it leaves some terms untypable for good. In , the variable is applied to itself, so its type must be a function type whose argument is itself: , 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 asks for a type substitution with .
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 , 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 is added, 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))),
}
}
bind refuses a variable that occurs in its value. code/bachelor-3/06-type-systems/listings/unify.rs'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 and have a unifier, unify returns a most general one; otherwise it fails.
Proof. We prove: if unify is called with a substitution , and is any unifier of and that is an instance of ( for some ), then unify succeeds with an of which is still an instance, and unifies the two types. The induction is on the number of variables not bound by , then on the size of the types. Write , . If is a variable and , then ; were to occur in , would contain as a proper subterm, so it could not equal it: the occurs check fails only when there is no unifier. Otherwise unifies, and is an instance of it, since already sends to . If both are arrows and , then unifies with and with ; the first recursive call gives of which is an instance, and the second call, on smaller types or with fewer unbound variables, gives . If the two have different constructors, no substitution can make them equal. Taking 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 -bound variable gets a fresh type variable. An application infers and , takes a fresh and unifies with . 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 }
}
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)?
}
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)
$ 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
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 -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
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 derives it from a derivation of under the hypothesis , and its elimination rule (modus ponens) derives from and ; is introduced from and , 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 -calculus, where every term terminates, a closed term of type is a proof of the proposition read with as implication and as conjunction, and reducing the term simplifies the proof.
The principal type of swap in Output 6.2, , is the tautology , 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"));
}
$ rustc --edition 2021 -O -o curry_howard curry_howard.rs && ./curry_howard
("one", 1) true false
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
}
$ 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
|
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.
; ; (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 . \f. \x. f x x: . \p. fst p + snd p: . \x. if x then x else 1: none; the condition makes a , and the branches have types and (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: is applied to and to its own result, so its argument and result types are equal, and so is the type of (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.
gets , and the application asks . Without the check, the binding is stored. Resolving replaces it by , whose 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 occurs in , then for any substitution , is a proper subterm of , hence smaller, so .
Exercise 6.6 ★★
The checker of Listing 6.1 rejects pairs. Write the rules for , 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.
exercises/ex6_pairs.rs adds the three arms. The test types the example as , a pair holding a function as , 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 , then for bindings of variables not free in , by induction on the derivation (each rule only looks up the free variables of ). Now induct on the derivation of . If is , then and , and weakening of gives . If is another variable or a constant, the substitution changes nothing and the binding of was not used. If , rename so that ( is closed, so is not free in it); the premise is , which is also derivable with the two bindings exchanged, since they concern different names; the induction hypothesis gives , 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 , the annotation fixes and the induction hypothesis fixes the type of in the extended context, hence the arrow. For , the hypothesis fixes ’s type, which must be some , and the result is that . 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 , , and every other . 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, has the scheme , and each use takes a fresh instance: the function position , the argument . The result is , printed 'a -> 'a. Bound by , has one type throughout the body, and requires , 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.
The step gives with . By the substitution lemma applied to the second premise, it suffices that . By abs, that is , and by the rule itself it needs and . The first premise of the original rule, with empty since the program is closed, gives both: the outer binding of 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, keeps the type with a variable shared by both uses; id 1 solves , and id true then asks , 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 to a value and continues with : each occurrence of becomes its own copy of , and since the generalised variables do not occur in , the derivation of ’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 for a cell holding a . Show that generalising let r = ref (\x. x) in … lets a well-typed program apply a function of type to a boolean. State the value restriction, which generalises let x = e only when 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 ; the assignment uses the instance , the read the instance , and the program is typed. But there is one cell, not one per use: after the assignment it holds , and the program computes , stuck. The argument of exercise 6.11 broke because evaluating allocated a cell that all the copies share. The value restriction generalises let x = e1 in e2 only when 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 keeps a single type variable, and the program is rejected with a clash between and . 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 functions, each applying the previous one twice. blowup.rs builds it for , infers its principal type , and measures 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
unify, the leaves of , and its distinct subtrees.Part I — By hand.
- Infer the principal type of
\x. (x, x), writing every equation. - Infer the type of
let f0 = \x. (x, x) in \x. f0 (f0 x). Where are the two instances of ’s scheme used? - What is the type of
f0 (f0 1)? - Why is
(\f0. \x. f0 (f0 x)) (\x. (x, x))rejected? Write the equation that fails. - Write and .
- How does the program’s length grow with ?
Part II — The family.
- Show that for , with .
- Deduce the number of leaves of : give a recurrence, then a closed form.
- Give the depth of .
- Count the distinct subtrees of , and explain the column of Output 6.6.
- Check the three formulas against the table.
- What would the row say? Why does the program not print it?
Part III — Where the time goes.
- The unify calls grow by 6 per line. Which equations does each
letline contribute? - If unification is called so few times, where does the work of inference go when types are trees?
- Estimate the memory for as a tree, at 16 bytes per node.
- With types as graphs (each subtree shared), what is the size of ? Is inference then polynomial in the program’s length?
- Printing costs its number of leaves at least. What does this say of any algorithm that outputs principal types as text?
- 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.
- 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. - Real programs nest
lets deeply. Why do their types stay small? - What does a type annotation on
f1change for the checker’s work? - Would the explosion happen in the simply typed core, where each parameter carries its type? Where would the size go?
- What does a compiler with inference do to keep its error messages readable when a type is large?
- Sum up: give the size of 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. ; the pair has type ; the abstraction . There is no application, so no equation at all.
2. . With , the inner use is instantiated as , and gives , . The outer use is instantiated afresh, , and unifying with gives . The type is : the two instances are at and at .
3. .
4. is a parameter, with one type. Its two uses force argument and result types to be equal, so , and the argument then asks , that is , which the occurs check refuses.
5. ; with each of replaced by , that is : 16 leaves.
6. characters: linearly.
7. With , the inner use of gives , and the outer use is an instance applied to that, so its result is ; up to the name of , .
8. Each of the leaves of is replaced by a copy of : , , so .
9. The depth doubles: , , so .
10. is a complete binary tree of products, all of whose leaves are , so all its subtrees at the same depth are equal. There is one distinct subtree per depth, from the root to the leaves: .
11. Leaves 2, 4, 16, 256, 65,536 are ; distinct subtrees 2, 3, 5, 9, 17 are ; lengths 25, 51, 77, 103, 129 are .
12. Length 155, 30 unify calls, leaves, 33 distinct subtrees. The tree has more than eight billion nodes and does not fit in the laptop’s memory.
13. Each line has two applications; each unifies an instance of an arrow with , which is one call for the two arrows and two recursive calls for their children: 6 calls per line, and none for .
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, leaves at line .
15. A tree with leaves has nodes, about , so about 137 GB.
16. nodes. Inference with shared types does work proportional to that size at each line, which is exponential in , hence in the program’s length: still not polynomial.
17. Writing out as text takes at least 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, and every is . Without the doubling, and . Without let (parameters instead), the family is rejected, question 4: polymorphism is what lets 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 : annotating means writing a type of leaves, so the cost moves into the program.
22. No polymorphism means one copy of each 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 has leaves; as a graph nodes. With trees, inference on this family takes time doubly exponential in the program’s length; with sharing, exponential.