Algorithm Search⌘K

Theoremadvanced

DEXPTIME-completeness of ML typability

Also called Mairson's theorem on ML typing.

Deciding whether an ML program is typable is complete for deterministic exponential time, since nested lets can double type sizes.

Deciding whether a program of core ML has a type is complete for DEXPTIME, the class of problems that a deterministic machine solves in time 2nk2^{n^k} for some fixed kk. The upper bound comes from typing each let as if its definition were copied at each use. The lower bound simulates any exponential time Turing machine by a short ML term whose type inference does the computation. Mairson (1990) and Kfoury, Tiuryn and Urzyczyn (1990) proved the result independently. It explains why algorithm W is exponential in the worst case, and it shows that no faster algorithm exists. In practice the hard terms do not occur, and ML compilers infer types quickly.

Statement

ML typability is the problem: given a closed term ee of the Hindley-Milner type system, with fun, application, let, constants, if and operators, decide whether ⊢e:τ\vdash e : \tau for some type τ\tau. Write n=∣e∣n = |e| for the number of nodes of ee. DEXPTIME, also written EXPTIME, is ⋃kDTIME(2nk)\bigcup_k \mathrm{DTIME}(2^{n^k}).

Theorem (Mairson 1990; Kfoury, Tiuryn and Urzyczyn 1990).

  1. Upper bound. ML typability can be decided in time 2O(n)2^{O(n)}.
  2. Lower bound. For each problem LL in DEXPTIME there is a function ff, computable in polynomial time, such that w∈Lw \in L if and only if the term f(w)f(w) is typable. So ML typability is DEXPTIME-hard under polynomial-time reductions, and with part 1 it is DEXPTIME-complete.
  3. Size of types. The principal type of a typable term has 2O(n)2^{O(n)} nodes when equal subtrees are shared, and 22O(n)2^{2^{O(n)}} nodes when it is written as a tree. Both bounds are reached.

In plain words

An ML compiler finds the types of a program with no help. This theorem says how hard that job can be in the worst case.

The answer is: exponentially hard. When a helper function is defined with let and used twice, the compiler in effect types two copies of it. If each helper is built from two uses of the one before, the copies double at each level. A short program can then stand for an enormous one.

The hard direction shows that this doubling is strong enough to run any computer program that finishes in exponential time. True and false become two shapes of type, gates become small functions, and the compiler's matching of types does the computing. So a fast type checker for ML would give a fast way to run all those programs, and that is known to be impossible.

Proof

The full argument is in the proof file. Here is its structure.

Upper bound. The key fact is that let is typed by copying: let x=e1 in e2\texttt{let } x = e_1 \texttt{ in } e_2 has the type τ\tau exactly when e1e_1 has some type and [x:=e1] e2[x := e_1]\,e_2 has the type τ\tau (Pierce, Section 22.7). The proof of the "if" direction uses the principal type theorem: all types of the copies are instances of one scheme of e1e_1. Expanding every let in this way, with an extra unused argument so that an unused definition is still checked, gives a term with no let and with the same types. Its size is at most 4n4^n, by induction on the term. A term with no let is typable exactly when a set of O(N)O(N) equations has a unifier, and unification on a term DAG solves this in almost linear time. So the total time is 2O(n)2^{O(n)}.

Size bounds. The expanded term has at most 4n4^n nodes, so the unification DAG and the principal type have 2O(n)2^{O(n)} nodes. A DAG with DD nodes unfolds to a tree with at most 2D+12^{D+1} nodes. The family $f_0 = $ fun x -> fun z -> z x x, $f_i = $ fun y -> f(i-1) (f(i-1) y) reaches both bounds: its term has 7k+97k + 9 nodes, and its principal type has 2k+2+22^{k+2} + 2 nodes as a DAG and 6⋅22k−36 \cdot 2^{2^k} - 3 nodes as a tree.

Lower bound. Take a deterministic Turing machine MM that runs in time 2p(n)2^{p(n)}, and an input ww.

  • Truth values as types. fun x -> fun y -> x has a type of the form α→β→α\alpha \to \beta \to \alpha, and fun x -> fun y -> y one of the form α→β→β\alpha \to \beta \to \beta. The test (b 1 true) + 1 is typable for the first and not for the second.
  • Gates. not = fun p -> p f t, and = fun p -> fun q -> p q f and or = fun p -> fun q -> p t q compute the right shape of result type by unification. Because a fun-bound variable has one type, each wire is used once, and fan-out goes through copy = fun p -> p (pair t t) (pair f f).
  • Exponential size and time. A step of MM on a tape of 2p(n)2^{p(n)} cells is built level by level with let, each level from two uses of the one below. Then let run_i = fun s -> run_(i-1) (run_(i-1) s) repeats the step 2p(n)2^{p(n)} times with only p(n)p(n) definitions.
  • Correctness. By the copying property, the term is typable exactly when its expansion is. In the expansion each fun-bound variable occurs at most once, and for such terms beta reduction keeps the types in both directions. The expansion reduces to 1 + 1 if MM accepts ww, and to true + 1 if not.

The proof file gives the upper bound and the size bounds in full, and the lower bound as a sketch. Mairson (1990) gives the complete simulation.

Consequences

  • W is exponential, not cubic. No algorithm decides ML typability in polynomial time, because DEXPTIME contains problems outside P by the time hierarchy theorem. Every inference algorithm for HM, W, J and the constraint-based ones, has an exponential worst case.
  • Sharing is needed for the upper bound. An implementation that copies types as trees takes doubly exponential time on the family fkf_k. Algorithm J with union-find works on a DAG and stays within 2O(n)2^{O(n)}.
  • The hardness carries over. Each language that contains core ML typing with polymorphic let, such as Standard ML, OCaml, F# and Haskell, has a DEXPTIME-hard type inference problem. Adding features can only make it harder: polymorphic recursion makes it undecidable.
  • Error messages can be huge. A type error in a term like fkf_k can involve a type with millions of nodes. A compiler that prints types as trees can print output of doubly exponential size.

Tightness

  • Without let. Typability in the simply typed lambda calculus needs only one unification problem of linear size. It takes linear time with the Paterson-Wegman algorithm. So the whole cost comes from let-polymorphism.
  • Bounded nesting. If the nesting depth of let is bounded by a constant dd, the bound of Lemma 3 of the proof file becomes polynomial: each level of nesting at most squares the size, so the expansion has at most about n2dn^{2^{d}} nodes, and typability is in polynomial time. McAllester (2003) gives a nearly linear bound for programs whose types have bounded order and arity. Real programs are close to this case.
  • The size bounds are exact in form. The family fkf_k has a principal type of DAG size 2Θ(n)2^{\Theta(n)} and tree size 22Θ(n)2^{2^{\Theta(n)}}.
  • Checking a given type is no easier in general: given ee and τ\tau, deciding ⊢e:τ\vdash e : \tau is also DEXPTIME-hard, since the term of the lower bound has type int\mathsf{int} when it has a type at all.
Proof: ML typability is in DEXPTIME, and it is DEXPTIME-hardsketch

This file proves the two halves of the theorem. The upper bound (part 1) and the size bounds (part 3) have full proofs. They use only the principal type theorem and the copying property of let. The lower bound (part 2) is a sketch of a simulation of an exponential time Turing machine. It follows the plan of Mairson (1990): truth values are encoded as types, a circuit is computed by type inference, and nested let repeats a step exponentially many times. The encoding of the tape below is one way to fill in the plan. Mairson (1990) and Kfoury, Tiuryn and Urzyczyn (1990, 1994) give complete proofs.

Setting

Terms, types and the syntax-directed rules are those of the Hindley-Milner page, with T-Var', T-Abs, T-App and T-Let', the constants, if and the operators. The size ∣e∣|e| of a term is the number of nodes of its syntax tree. A variable or a constant has size 1, and each fun, application, let, if and operator adds 1 to the sizes of its parts. We rename bound term variables so that they are all different and different from the free variables, which changes no size and no type.

Two standard facts about derivations are used. Type substitution: if Γ⊢e:τ\Gamma \vdash e : \tau, then SΓ⊢e:SτS\Gamma \vdash e : S\tau. Weakening and strengthening: adding to Γ\Gamma a binding for a variable that is not free in ee, or removing one, does not change the types of ee. Both are proved by induction on derivations, after the generalized variables of each inner let are renamed apart. Weakening is the lemma on a more general context of the W proof in a special case.

Lemma 1: let by copying

Lemma 1. Let x∉dom(Γ)x \notin \mathrm{dom}(\Gamma). Then Γ⊢let x=e1 in e2:τ\Gamma \vdash \texttt{let } x = e_1 \texttt{ in } e_2 : \tau if and only if Γ⊢e1:τ1\Gamma \vdash e_1 : \tau_1 for some τ1\tau_1 and Γ⊢[x:=e1] e2:τ\Gamma \vdash [x := e_1]\,e_2 : \tau.

Proof. (Only if.) T-Let' gives Γ⊢e1:τ1\Gamma \vdash e_1 : \tau_1 and Γ,x:σ⊢e2:τ\Gamma, x : \sigma \vdash e_2 : \tau with σ=Gen(Γ,τ1)\sigma = \mathrm{Gen}(\Gamma, \tau_1). Each leaf of the second derivation that uses xx is a T-Var' step Γ,Δ,x:σ⊢x:τ′\Gamma, \Delta, x : \sigma \vdash x : \tau' with σ⊑τ′\sigma \sqsubseteq \tau'. The substitution that sends the bound variables of σ\sigma to the chosen types does not touch ftv(Γ)\mathrm{ftv}(\Gamma), so type substitution gives Γ⊢e1:τ′\Gamma \vdash e_1 : \tau', and weakening gives Γ,Δ⊢e1:τ′\Gamma, \Delta \vdash e_1 : \tau'. Put this derivation in place of the leaf. The result is a derivation of Γ⊢[x:=e1] e2:τ\Gamma \vdash [x := e_1]\,e_2 : \tau.

(If.) If xx does not occur in e2e_2, use T-Let' with Gen(Γ,τ1)\mathrm{Gen}(\Gamma, \tau_1) and weakening. Otherwise let τ1′,…,τm′\tau_1', \ldots, \tau_m' be the types of the mm copies of e1e_1 in the derivation of [x:=e1] e2[x := e_1]\,e_2. By strengthening, Γ⊢e1:τj′\Gamma \vdash e_1 : \tau_j' for each jj. We need one type τ∗\tau^* with Γ⊢e1:τ∗\Gamma \vdash e_1 : \tau^* such that each τj′\tau_j' is an instance of Gen(Γ,τ∗)\mathrm{Gen}(\Gamma, \tau^*).

Let W(Γ,e1)=(S,τ0)W(\Gamma, e_1) = (S, \tau_0). By the completeness of W (in the proof file of algorithm W) with RR the identity, for each jj there is RjR_j with Rjτ0=τj′R_j\tau_0 = \tau_j' and RjSΓ=ΓR_j S \Gamma = \Gamma. All the RjR_j agree on the variables of SΓS\Gamma, because RjαR_j\alpha is the subterm of Γ\Gamma at the place where α\alpha occurs in SΓS\Gamma. So these images only contain variables of Γ\Gamma. Let R∗R^* agree with them on ftv(SΓ)\mathrm{ftv}(S\Gamma), and let it send each other variable of τ0\tau_0 to its own fresh variable. Put τ∗=R∗τ0\tau^* = R^*\tau_0. By the soundness of W and type substitution, Γ=R∗SΓ⊢e1:τ∗\Gamma = R^*S\Gamma \vdash e_1 : \tau^*. The substitution QjQ_j that sends each fresh variable back to the image of its original under RjR_j gives Qjτ∗=τj′Q_j\tau^* = \tau_j', and it only moves fresh variables, which are not free in Γ\Gamma. So Gen(Γ,τ∗)⊑τj′\mathrm{Gen}(\Gamma, \tau^*) \sqsubseteq \tau_j'. Replace the derivation of each copy by a T-Var' step for x:Gen(Γ,τ∗)x : \mathrm{Gen}(\Gamma, \tau^*) at the instance τj′\tau_j'. This gives Γ,x:Gen(Γ,τ∗)⊢e2:τ\Gamma, x : \mathrm{Gen}(\Gamma, \tau^*) \vdash e_2 : \tau, and T-Let' finishes. □\square

Lemma 2: the expansion

Define a term exp(e)\mathrm{exp}(e) with no let. It commutes with every form of term except let, and

exp(let x=e1 in e2)=(fun z -> [x:=exp(e1)] exp(e2)) exp(e1),\mathrm{exp}(\texttt{let } x = e_1 \texttt{ in } e_2) = (\texttt{fun } z \texttt{ -> } [x := \mathrm{exp}(e_1)]\,\mathrm{exp}(e_2))\ \mathrm{exp}(e_1),

with zz fresh. The extra argument makes sure that e1e_1 is checked even when xx is not used.

Lemma 2. For each Γ\Gamma and τ\tau: Γ⊢e:τ\Gamma \vdash e : \tau if and only if Γ⊢exp(e):τ\Gamma \vdash \mathrm{exp}(e) : \tau.

Proof. By induction on ee, for all Γ\Gamma at once. All cases but let follow from the induction hypothesis, since the rules for them only look at the types of the parts. For let, write ei′=exp(ei)e_i' = \mathrm{exp}(e_i). By T-Let' and the induction hypothesis in the contexts Γ\Gamma and Γ,x:Gen(Γ,τ1)\Gamma, x : \mathrm{Gen}(\Gamma, \tau_1), the term let x=e1 in e2\texttt{let } x = e_1 \texttt{ in } e_2 has the same types as let x=e1′ in e2′\texttt{let } x = e_1' \texttt{ in } e_2'. By Lemma 1, these are the types of [x:=e1′] e2′[x := e_1']\,e_2', under the condition that e1′e_1' has a type. T-App and T-Abs with an unused zz express exactly this condition. □\square

Lemma 3. ∣exp(e)∣≤4∣e∣|\mathrm{exp}(e)| \le 4^{|e|}.

Proof. By induction on ee. A variable or constant has size 1≤41 \le 4. For fun, 1+4a≤4a+11 + 4^a \le 4^{a+1}. For an application, 1+4a+4b≤4a+b+11 + 4^a + 4^b \le 4^{a+b+1}, and the cases of if and the operators are the same. For let with ∣e1∣=a|e_1| = a and ∣e2∣=b|e_2| = b, let A=∣exp(e1)∣A = |\mathrm{exp}(e_1)| and B=∣exp(e2)∣B = |\mathrm{exp}(e_2)|. If xx occurs m≤Bm \le B times in exp(e2)\mathrm{exp}(e_2), then ∣[x:=exp(e1)] exp(e2)∣=B−m+mA≤BA|[x := \mathrm{exp}(e_1)]\,\mathrm{exp}(e_2)| = B - m + mA \le BA. So

∣exp(e)∣≤2+BA+A≤2+4a+b+4a≤4a+b+1=4∣e∣,|\mathrm{exp}(e)| \le 2 + BA + A \le 2 + 4^{a+b} + 4^a \le 4^{a+b+1} = 4^{|e|},

because 3⋅4a+b≥12⋅4a>4a+23 \cdot 4^{a+b} \ge 12 \cdot 4^a > 4^a + 2. □\square

Part 1: the upper bound

Let n=∣e∣n = |e|. Compute exp(e)\mathrm{exp}(e) in time proportional to its size, which is at most 4n4^n by Lemma 3. By Lemma 2, ee is typable exactly when exp(e)\mathrm{exp}(e) is. A term with no let is typable exactly when the set of equations with one type variable per node, αe1=αe2→αe1e2\alpha_{e_1} = \alpha_{e_2} \to \alpha_{e_1 e_2} at each application and so on, has a unifier. There are O(N)O(N) equations for a term of size NN. Unification on a term DAG with union-find solves them in O(N α(N))O(N\,\alpha(N)) time, and the Paterson-Wegman algorithm in O(N)O(N) time. So typability is decided in time O(4n)=2O(n)O(4^n) = 2^{O(n)}, which is inside DEXPTIME. □\square

Part 3: the size of principal types

By Lemma 2, the principal type of ee is the principal type of exp(e)\mathrm{exp}(e), up to renaming. Unification on a DAG never creates more nodes than it starts with, so the principal type is a DAG with O(4n)O(4^n) nodes. A DAG with DD nodes of out-degree at most 2 has each root path of length at most DD, so its tree form has at most 2D+12^{D+1} nodes. This gives the bounds 2O(n)2^{O(n)} and 22O(n)2^{2^{O(n)}}.

Both bounds are reached. In the family

let f0 = fun x -> fun z -> z x x in
let f1 = fun y -> f0 (f0 y) in
...
let fk = fun y -> f(k-1) (f(k-1) y) in fk

the type of f0f_0 is α→(α→α→β)→β\alpha \to (\alpha \to \alpha \to \beta) \to \beta. The function fif_i applies f0f_0 2i2^i times in a row, and each application puts two copies of the previous type into the next one. So the principal type of the term, of size 7k+97k + 9, has 2k+2+22^{k+2} + 2 nodes as a DAG and 6⋅22k−36 \cdot 2^{2^k} - 3 nodes as a tree. Any algorithm that writes types as trees, as a plain implementation of W does, takes doubly exponential time on this family.

Part 2: the lower bound (sketch)

Let LL be in DEXPTIME. Then a deterministic one-tape Turing machine MM decides LL in time 2p(n)2^{p(n)} for a polynomial pp. Fix an input ww of length nn and let m=p(n)m = p(n), large enough that 2m≥n2^m \ge n. We may assume that MM uses at most 2m2^m cells and stays in its accepting state once it gets there. We build, in polynomial time, a term ewe_w of size polynomial in nn that is typable if and only if MM accepts ww.

Step 1: truth values as types. Let t = fun x -> fun y -> x and f = fun x -> fun y -> y, both bound by let. Their schemes are ∀αβ. α→β→α\forall \alpha \beta.\, \alpha \to \beta \to \alpha and ∀αβ. α→β→β\forall \alpha \beta.\, \alpha \to \beta \to \beta. Call a type of the form α→β→α\alpha \to \beta \to \alpha a true type and one of the form α→β→β\alpha \to \beta \to \beta a false type, when α\alpha and β\beta are type variables that occur nowhere else in the derivation. For the test (b 1 true) + 1, a true type of b gives int\mathsf{int}, and a false type needs bool=int\mathsf{bool} = \mathsf{int}, so the test fails.

Step 2: gates. Define, with let,

let pair = fun a -> fun b -> fun k -> k a b
let not  = fun p -> p f t
let and  = fun p -> fun q -> p q f
let or   = fun p -> fun q -> p t q
let copy = fun p -> p (pair t t) (pair f f)

If p has a true or false type, unification of that type with the argument types of a gate gives the result type of the gate: for example not applied to a true type unifies α→β→α\alpha \to \beta \to \alpha with F→T→ρF \to T \to \rho, where FF and TT are fresh false and true types, so ρ=F\rho = F. Each use of t, f and a gate is a fresh instance, so the result again has variables that occur nowhere else. In this way type inference computes the gate. A fun-bound variable has one type, so a wire must not be used twice. Fan-out goes through copy, which turns one truth value into a pair of two independent fresh truth values, read by a continuation fun u -> fun v -> .... So each Boolean circuit with ss gates becomes a term of size O(s)O(s) in which each fun-bound variable occurs at most once, and whose type inference evaluates the circuit.

Step 3: one step of the machine. Encode the content of a cell, a state or a tape symbol, as a tuple of cc truth values, where cc depends only on MM. As in the Cook-Levin theorem, the next content of cell ii is a fixed circuit of cells i−1i - 1, ii and i+1i + 1. Store the tape of 2m2^m cells as a complete binary tree of depth mm, built from pair. For i=0,1,…,mi = 0, 1, \ldots, m, define with let a function stepi\mathit{step}_i that takes a left neighbour cell, a tree of depth ii and a right neighbour cell and returns the next tree, and helper functions that copy a tree and that read its first and last cell. Each function of level ii is defined from the functions of level i−1i - 1. These are let-bound, so they may be used several times, each at a fresh instance. Inside each body, each fun-bound variable occurs at most once. Each level adds O(1)O(1) nodes, with a constant that depends on MM, so all levels together have size O(m)O(m).

Step 4: exponentially many steps. Let run0=stepm\mathit{run}_0 = \mathit{step}_m with blank boundary cells, and

let run1 = fun s -> run0 (run0 s) in
...
let runm = fun s -> run(m-1) (run(m-1) s) in ...

so that runm\mathit{run}_m performs 2m2^m steps, as in the family of part 3. The initial tape has ww in its first nn cells and blanks elsewhere. Blank trees of each depth come from let blank_i = pair blank_(i-1) blank_(i-1), and the cells of ww are placed along nn paths of length mm, which takes O(nm)O(nm) nodes. A last function of size O(m)O(m), built the same way, computes the "or" over all cells of the test "this cell holds the accepting state". Let ewe_w be the test of Step 1 applied to this truth value. Its size is polynomial in nn, and it is easy to produce from ww.

Step 5: correctness. By Lemma 2, ewe_w is typable exactly when exp(ew)\mathrm{exp}(e_w) is. All let definitions of ewe_w are closed and sit at the top, so the expansion copies no fun-bound variable, and in exp(ew)\mathrm{exp}(e_w) each fun-bound variable occurs at most once. For such terms, a beta step does not change the types: subject reduction holds in the simply typed calculus, and subject expansion holds when the bound variable occurs once, or when it does not occur and the discarded argument has a type. In the construction, each discarded argument is a truth value or a tuple of truth values, and it has a type. Each beta step makes the term smaller, so exp(ew)\mathrm{exp}(e_w) reduces to its normal form, which is 1 + 1 if MM accepts ww and true + 1 if not. The first has a type and the second has none. So ewe_w is typable if and only if MM accepts ww. □\square

References

  • Harry G. Mairson, Deciding ML typability is complete for deterministic exponential time, POPL 1990, pages 382 to 401. The lower bound by a simulation of an exponential time Turing machine.
  • A. J. Kfoury, J. Tiuryn and P. Urzyczyn, ML typability is DEXPTIME-complete, CAAP 1990, LNCS 431, pages 206 to 220, and An analysis of ML typability, Journal of the ACM 41(2), 1994, pages 368 to 398. An independent proof, by an equivalence of ML typability with acyclic semi-unification.
  • Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, Section 22.7. Typing let by substitution.
  1. Harry G. Mairson, Deciding ML typability is complete for deterministic exponential time, Seventeenth ACM Symposium on Principles of Programming Languages (POPL 1990), pages 382 to 401, the DEXPTIME-hardness proof by simulation of an exponential time Turing machine with nested let
  2. A. J. Kfoury, J. Tiuryn and P. Urzyczyn, ML typability is DEXPTIME-complete, CAAP 1990, Lecture Notes in Computer Science 431, pages 206 to 220, the main theorem, with ML typability shown log-space equivalent to acyclic semi-unification
  3. A. J. Kfoury, J. Tiuryn and P. Urzyczyn, An analysis of ML typability, Journal of the ACM 41(2), 1994, pages 368 to 398, the journal version of the CAAP 1990 paper, with the full proofs
  4. Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, Section 22.7 (typing let by substitution, and the remark that nested lets make types exponentially large)
  5. David McAllester, A logical algorithm for ML type inference, Rewriting Techniques and Applications (RTA 2003), Lecture Notes in Computer Science 2706, pages 436 to 451, the nearly linear time bound for programs whose types have bounded order and arity

History

Milner (1978) gave algorithm W. It was fast on real programs, and for about ten years its worst case was not known. Kanellakis and Mitchell (1989) showed that ML typability is PSPACE-hard. In 1990, Mairson closed the gap with DEXPTIME-hardness, by a direct simulation of Turing machines, and Kfoury, Tiuryn and Urzyczyn proved the same result independently. Their proof shows that ML typability is equivalent to acyclic semi-unification, a restricted form of the semi-unification problem. The journal version appeared in 1994. McAllester (2003) explained the good behavior in practice by a bound that is nearly linear when the order and arity of types are bounded.

References

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M7MW7Q/text.yaml