Algorithm Search⌘K

Algorithmcore

Algorithm W

Also called Damas-Milner algorithm W.

Infers the principal type of an ML term bottom-up by unification, generalizing free type variables at each let binding.

Time
2^(2^O(n)) worstΘ(n) best
Space
2^(2^O(n)) extra
Where
n = the number of nodes of the term
Properties
deterministicrecursive

Algorithm W computes the principal type of a term of the Hindley-Milner type system, or reports that the term has no type. It walks the term from the leaves up. At each variable it makes a fresh copy of the type scheme. At each application it calls unification to make the function type and the argument type fit. At each let it generalizes the type variables that the context does not mention. Milner (1978) designed it for ML, and Damas and Milner (1982) proved that it is sound and complete. It needs no type annotations at all. Its running time is exponential in the worst case, and doubly exponential if types are stored as trees, but on real programs it is fast.

In plain words

W reads a program and works out the type of each piece, from the smallest pieces up. When it meets a name it knows nothing about, it writes a placeholder, such as "some type a". When a function is applied to an argument, it compares the two types and fills in placeholders so that they fit. If they cannot fit, for example a number where a function is needed, the program has a type error. When a let gives a name to a finished piece, W marks the placeholders that nothing outside depends on as free to vary. Each later use of the name gets new copies of those placeholders, so one helper can work with numbers in one place and with text in another. The answer is the most general type: every other correct type for the program is a special case of it.

The problem

Input: a context Γ\Gamma that maps term variables to type schemes, and a term ee of the language x, fun x -> e, e1 e2, let x = e1 in e2, with constants, if, integer operators and fix f x -> e.

Output: a substitution SS and a type τ\tau with SΓ⊢e:τS\Gamma \vdash e : \tau in the Hindley-Milner rules, such that each other solution is an instance of (S,τ)(S, \tau). If no substitution RR and type τ′\tau' give RΓ⊢e:τ′R\Gamma \vdash e : \tau', the output is a failure. For a closed term, Γ\Gamma is empty and τ\tau is the principal type. This is the type inference problem for ML.

The algorithm

A substitution maps type variables to types. S2S1S_2 S_1 means "first S1S_1, then S2S_2". A variable is fresh if it was never used before. GEN(Γ,τ)\mathrm{GEN}(\Gamma, \tau) is the scheme ∀α⃗. τ\forall \vec\alpha.\, \tau, where α⃗\vec\alpha are the variables of τ\tau that are not free in Γ\Gamma. MGU is a most general unifier with the occurs check, for example Robinson's algorithm.

  1. W(Γ, e) ▷ returns (S, τ) with SΓ ⊢ e : τ, or fails
  2. 1if e is a variable x then let ∀α1 ... αk. τ be Γ(x) ▷ fail if x is not in Γ
  3. 2return (id, [α1 := β1, ..., αk := βk] τ) ▷ β1 ... βk fresh
  4. 3if e is fun x -> e1 then β ← fresh
  5. 4(S1, τ1) ← W((Γ, x : β), e1)
  6. 5return (S1, S1 β → τ1)
  7. 6if e is e1 e2 then (S1, τ1) ← W(Γ, e1)
  8. 7(S2, τ2) ← W(S1 Γ, e2)
  9. 8β ← fresh, S3 ← MGU(S2 τ1, τ2 → β) ▷ fail if there is no unifier
  10. 9return (S3 S2 S1, S3 β)
  11. 10if e is let x = e1 in e2 then (S1, τ1) ← W(Γ, e1)
  12. 11σ ← GEN(S1 Γ, τ1) ▷ only variables not free in S1 Γ
  13. 12(S2, τ2) ← W((S1 Γ, x : σ), e2)
  14. 13return (S2 S1, τ2)
  15. 14if e is fix f x -> e1 then α, β ← fresh, (S1, τ1) ← W((Γ, f : α → β, x : α), e1)
  16. 15S2 ← MGU(S1 β, τ1), return (S2 S1, S2 S1 (α → β))

Constants return their base type with the identity substitution. if e1 then e2 else e3 and e1 op e2 are like L6 to L9: they call W on each part in turn, apply each new substitution to the context, and unify the condition with bool\mathsf{bool}, the operands with int\mathsf{int} and the two branches with each other. Note that ff and xx in line L14 get plain types, not schemes. So a recursive function is monomorphic in its own body.

Example

Take let id = fun x -> x in id id. Write β0,β1,…\beta_0, \beta_1, \ldots for the fresh variables in the order W makes them.

step call result
L10 W(∅, fun x -> x) L3 makes β0\beta_0. The body x gives (id,β0)(\mathrm{id}, \beta_0), so the result is (id,β0→β0)(\mathrm{id}, \beta_0 \to \beta_0)
L11 GEN(∅, β0→β0\beta_0 \to \beta_0) σ=∀β0. β0→β0\sigma = \forall \beta_0.\, \beta_0 \to \beta_0, since the context is empty
L6 W(id : σ, id) a fresh copy β1→β1\beta_1 \to \beta_1
L7 W(id : σ, id) another fresh copy β2→β2\beta_2 \to \beta_2
L8 MGU(β1→β1\beta_1 \to \beta_1, (β2→β2)→β3(\beta_2 \to \beta_2) \to \beta_3) S3=[β1:=β2→β2, β3:=β2→β2]S_3 = [\beta_1 := \beta_2 \to \beta_2,\ \beta_3 := \beta_2 \to \beta_2]
L9 the type S3β3=β2→β2S_3\beta_3 = \beta_2 \to \beta_2

The principal type is a→aa \to a. The two uses of id got different instances, (β2→β2)→β2→β2(\beta_2 \to \beta_2) \to \beta_2 \to \beta_2 and β2→β2\beta_2 \to \beta_2, which is possible only because line L11 quantified β0\beta_0.

Now take fun x -> let y = x in if y true then y 1 else 0. Line L3 gives x the type β0\beta_0. At line L11 the context is x:β0x : \beta_0, so β0\beta_0 is free in it and GEN returns β0\beta_0 with no quantifier. Then y true unifies β0\beta_0 with bool→β1\mathsf{bool} \to \beta_1, and y 1 must unify bool→β1\mathsf{bool} \to \beta_1 with int→β2\mathsf{int} \to \beta_2, which fails. The term has no type, which is right: applied to 5, it would get stuck at 5 true.

Correctness

Two theorems say that W is correct. Soundness: if W(Γ,e)=(S,τ)W(\Gamma, e) = (S, \tau), then SΓ⊢e:τS\Gamma \vdash e : \tau. Completeness: if RΓ⊢e:τ′R\Gamma \vdash e : \tau' for some substitution RR, then W succeeds with (S,τ)(S, \tau), and τ′=R′τ\tau' = R'\tau and RΓ=R′SΓR\Gamma = R'S\Gamma for some R′R'. Both are proved by induction on ee. Soundness needs the type substitution lemma: if Γ⊢e:τ\Gamma \vdash e : \tau, then SΓ⊢e:SτS\Gamma \vdash e : S\tau. That lemma holds only because GEN skips the variables that are free in the context. Completeness needs the fact that R3=R4S3R_3 = R_4 S_3 for any unifier R3R_3 at line L8, which is the most general unifier property, and a lemma that a more general scheme in the context keeps each judgment true. For a closed term, the two theorems together say that W returns the principal type. The proof file proves both theorems in full for the syntax-directed rules. It cites Damas (1985) for the equivalence with the rules that have explicit generalization and instantiation steps.

Proof: Algorithm W is sound and complete for the Hindley-Milner rulesfull

This file proves in full that algorithm W is sound and complete for the syntax-directed rules of the Hindley-Milner type system: rules T-Var', T-Abs, T-App and T-Let'. The step from the syntax-directed rules to the declarative rules with T-Gen and T-Inst is cited. It is a separate induction on derivations, given in the thesis of Damas (1985), and outlined on the Hindley-Milner page. The proof follows the plan of Damas and Milner (1982). The forms if, the operators and fix add cases that are the same as the application case, so we leave them out.

Setting

A substitution SS maps type variables to types and is the identity on all but finitely many. SS acts on a type by replacing each variable at once. On a scheme ∀α⃗. τ\forall \vec\alpha.\, \tau, we first rename α⃗\vec\alpha to variables that SS does not touch and that do not occur in the range of SS, and then apply SS to the body. SS′S S' is the composition: first S′S', then SS. Schemes are equal up to renaming of bound variables and removal of bound variables that do not occur in the body.

A scheme σ′\sigma' is more general than σ\sigma, written σ′⊒σ\sigma' \sqsupseteq \sigma, if each instance of σ\sigma is an instance of σ′\sigma'. Contexts are compared name by name.

W returns a pair (S,τ)(S, \tau) or fails. It calls MGU, the most general unifier of Robinson's algorithm. We use two facts about MGU. If MGU(τ1,τ2)(\tau_1, \tau_2) returns UU, then Uτ1=Uτ2U\tau_1 = U\tau_2. If some RR has Rτ1=Rτ2R\tau_1 = R\tau_2, then MGU(τ1,τ2)(\tau_1, \tau_2) succeeds and returns a UU with R=R′UR = R' U for some R′R'. The variables in UU all occur in τ1\tau_1 or τ2\tau_2 (see most general unifier).

Fresh variables. W takes each fresh variable from a global supply, so it is new to the whole run. A call W(Γ,e)W(\Gamma, e) creates the fresh variables that it and its nested calls take. Each variable in the result (S,τ)(S, \tau) is free in Γ\Gamma or created by the call. This follows from the cases of W below and from the fact about the variables of MGU.

Two lemmas on derivations

Lemma 1 (a more general context). If Γ,x:σ⊢e:τ\Gamma, x : \sigma \vdash e : \tau and σ′⊒σ\sigma' \sqsupseteq \sigma, then Γ,x:σ′⊢e:τ\Gamma, x : \sigma' \vdash e : \tau.

Proof. First, ftv(σ′)⊆ftv(σ)\mathrm{ftv}(\sigma') \subseteq \mathrm{ftv}(\sigma). Write σ′=∀α⃗. τ′\sigma' = \forall \vec\alpha.\, \tau'. Rename the bound variables of σ\sigma to variables that do not occur in σ′\sigma', so that σ=∀β⃗. τ\sigma = \forall \vec\beta.\, \tau. The body τ\tau is an instance of σ\sigma, so τ=Rτ′\tau = R\tau' for an RR that changes only α⃗\vec\alpha. A free variable γ\gamma of σ′\sigma' occurs in τ′\tau', and Rγ=γR\gamma = \gamma, so γ\gamma occurs in τ\tau. It is not in β⃗\vec\beta, so γ∈ftv(σ)\gamma \in \mathrm{ftv}(\sigma).

Now use induction on the derivation, for all contexts in which some names have more general schemes. At T-Var', an instance of σ\sigma is an instance of σ′\sigma'. At T-Let', the generalization of the new context quantifies at least the variables that the old one quantifies, because the new context has no more free variables. So the scheme for the let-bound name is more general, and the induction hypothesis applies to the body. The other rules do not look at the context. □\square

Lemma 2 (type substitution). If Γ⊢e:τ\Gamma \vdash e : \tau, then SΓ⊢e:SτS\Gamma \vdash e : S\tau for each substitution SS, by a derivation of the same height.

Proof. Induction on the height of the derivation, for all SS at once. T-Abs and T-App follow from the induction hypothesis. At T-Var', Γ(x)=∀α⃗. τ0\Gamma(x) = \forall \vec\alpha.\, \tau_0 and τ=[α⃗:=ρ⃗] τ0\tau = [\vec\alpha := \vec\rho]\,\tau_0. Rename α⃗\vec\alpha so that SS does not touch these variables and they do not occur in the range of SS. Then S(∀α⃗. τ0)=∀α⃗. Sτ0S(\forall\vec\alpha.\, \tau_0) = \forall\vec\alpha.\, S\tau_0, and Sτ=[α⃗:=Sρ⃗] (Sτ0)S\tau = [\vec\alpha := S\vec\rho]\,(S\tau_0) is an instance of it.

At T-Let', the premises are Γ⊢e1:τ1\Gamma \vdash e_1 : \tau_1 and Γ,x:∀α⃗. τ1⊢e2:τ\Gamma, x : \forall\vec\alpha.\, \tau_1 \vdash e_2 : \tau, where α⃗=ftv(τ1)∖ftv(Γ)\vec\alpha = \mathrm{ftv}(\tau_1) \setminus \mathrm{ftv}(\Gamma). Choose new variables β⃗\vec\beta that do not occur in Γ\Gamma, τ1\tau_1 or SS, and let P=[α⃗:=β⃗]P = [\vec\alpha := \vec\beta]. By the induction hypothesis with SPSP, SPΓ⊢e1:SPτ1SP\Gamma \vdash e_1 : SP\tau_1. Since α⃗\vec\alpha is not free in Γ\Gamma, SPΓ=SΓSP\Gamma = S\Gamma. The variables β⃗\vec\beta are not free in SΓS\Gamma, so Gen(SΓ,SPτ1)\mathrm{Gen}(S\Gamma, SP\tau_1) quantifies all of β⃗\vec\beta and is more general than ∀β⃗. SPτ1\forall \vec\beta.\, SP\tau_1, which is S(∀α⃗. τ1)S(\forall \vec\alpha.\, \tau_1). By the induction hypothesis with SS on the second premise, SΓ,x:S(∀α⃗. τ1)⊢e2:SτS\Gamma, x : S(\forall\vec\alpha.\, \tau_1) \vdash e_2 : S\tau. By Lemma 1, the same holds with x:Gen(SΓ,SPτ1)x : \mathrm{Gen}(S\Gamma, SP\tau_1). T-Let' gives SΓ⊢let x=e1 in e2:SτS\Gamma \vdash \texttt{let } x = e_1 \texttt{ in } e_2 : S\tau. Lemma 1 does not increase the height, so the heights stay the same. □\square

The side condition of generalization is used in the step SPΓ=SΓSP\Gamma = S\Gamma. If Gen\mathrm{Gen} also quantified variables that are free in Γ\Gamma, this step and Lemma 2 would fail, and so would soundness.

Soundness

Theorem 1 (soundness). If W(Γ,e)=(S,τ)W(\Gamma, e) = (S, \tau), then SΓ⊢e:τS\Gamma \vdash e : \tau.

Proof. Induction on ee.

  • Variable (lines L1 and L2). Γ(x)=∀α⃗. τ0\Gamma(x) = \forall\vec\alpha.\, \tau_0, SS is the identity, and τ=[α⃗:=β⃗] τ0\tau = [\vec\alpha := \vec\beta]\,\tau_0 is an instance. T-Var' applies.
  • Abstraction (lines L3 to L5). By induction, S1Γ,x:S1β⊢e1:τ1S_1\Gamma, x : S_1\beta \vdash e_1 : \tau_1. T-Abs gives S1Γ⊢fun x -> e1:S1β→τ1S_1\Gamma \vdash \texttt{fun } x \texttt{ -> } e_1 : S_1\beta \to \tau_1.
  • Application (lines L6 to L9). By induction, S1Γ⊢e1:τ1S_1\Gamma \vdash e_1 : \tau_1 and S2S1Γ⊢e2:τ2S_2S_1\Gamma \vdash e_2 : \tau_2. By Lemma 2 with S3S2S_3S_2 and with S3S_3, S3S2S1Γ⊢e1:S3S2τ1S_3S_2S_1\Gamma \vdash e_1 : S_3S_2\tau_1 and S3S2S1Γ⊢e2:S3τ2S_3S_2S_1\Gamma \vdash e_2 : S_3\tau_2. Line L8 gives S3S2τ1=S3τ2→S3βS_3S_2\tau_1 = S_3\tau_2 \to S_3\beta. T-App gives the type S3βS_3\beta.
  • Let (lines L10 to L13). By induction, S1Γ⊢e1:τ1S_1\Gamma \vdash e_1 : \tau_1 and S2(S1Γ,x:σ)⊢e2:τ2S_2(S_1\Gamma, x : \sigma) \vdash e_2 : \tau_2 with σ=Gen(S1Γ,τ1)\sigma = \mathrm{Gen}(S_1\Gamma, \tau_1). Exactly as in the let case of Lemma 2, with S2S_2 in place of SS and S1ΓS_1\Gamma in place of Γ\Gamma, there is a type τ1′\tau_1' with S2S1Γ⊢e1:τ1′S_2S_1\Gamma \vdash e_1 : \tau_1' and Gen(S2S1Γ,τ1′)⊒S2σ\mathrm{Gen}(S_2S_1\Gamma, \tau_1') \sqsupseteq S_2\sigma. Lemma 1 and T-Let' give S2S1Γ⊢let x=e1 in e2:τ2S_2S_1\Gamma \vdash \texttt{let } x = e_1 \texttt{ in } e_2 : \tau_2. □\square

Completeness

Theorem 2 (completeness). Let RR be a substitution with RΓ⊢e:τ′R\Gamma \vdash e : \tau'. Then W(Γ,e)W(\Gamma, e) succeeds with a result (S,τ)(S, \tau), and there is a substitution R′R' with R′τ=τ′R'\tau = \tau' and R′Sα=RαR'S\alpha = R\alpha for each variable α\alpha that the call did not create.

Proof. Induction on ee, for all Γ\Gamma, RR and τ′\tau'. The variables created by the call are fresh, so they do not occur in Γ\Gamma, and we may change RR on them freely.

Variable. Let Γ(x)=∀α⃗. τ0\Gamma(x) = \forall\vec\alpha.\, \tau_0, with α⃗\vec\alpha apart from RR. The judgment RΓ⊢x:τ′R\Gamma \vdash x : \tau' comes from T-Var', so τ′=[α⃗:=ρ⃗] Rτ0\tau' = [\vec\alpha := \vec\rho]\,R\tau_0 for some types ρ⃗\vec\rho. W returns (id,[α⃗:=β⃗] τ0)(\mathrm{id}, [\vec\alpha := \vec\beta]\,\tau_0) with fresh β⃗\vec\beta. Let R′R' be RR with β⃗:=ρ⃗\vec\beta := \vec\rho. Then R′[α⃗:=β⃗] τ0=[α⃗:=ρ⃗] Rτ0=τ′R'[\vec\alpha := \vec\beta]\,\tau_0 = [\vec\alpha := \vec\rho]\,R\tau_0 = \tau', and R′=RR' = R on each old variable.

Abstraction. The judgment comes from T-Abs, so τ′=τa→τb\tau' = \tau_a \to \tau_b and RΓ,x:τa⊢e1:τbR\Gamma, x : \tau_a \vdash e_1 : \tau_b. Let R0R_0 be RR with β:=τa\beta := \tau_a, for the fresh β\beta of line L3. Then R0(Γ,x:β)=RΓ,x:τaR_0(\Gamma, x : \beta) = R\Gamma, x : \tau_a. By induction, W(Γ,x:β; e1)=(S1,τ1)W(\Gamma, x : \beta;\ e_1) = (S_1, \tau_1) with an R1R_1 such that R1τ1=τbR_1\tau_1 = \tau_b and R1S1=R0R_1S_1 = R_0 on the variables not created by that call. In particular R1S1β=τaR_1S_1\beta = \tau_a. So R1(S1β→τ1)=τ′R_1(S_1\beta \to \tau_1) = \tau'. Take R′=R1R' = R_1.

Application. The judgment comes from T-App, so RΓ⊢e1:τa→τ′R\Gamma \vdash e_1 : \tau_a \to \tau' and RΓ⊢e2:τaR\Gamma \vdash e_2 : \tau_a.

  1. By induction on e1e_1: W(Γ,e1)=(S1,τ1)W(\Gamma, e_1) = (S_1, \tau_1) and R1τ1=τa→τ′R_1\tau_1 = \tau_a \to \tau', with R1S1=RR_1S_1 = R on old variables. So R1(S1Γ)=RΓR_1(S_1\Gamma) = R\Gamma.
  2. So R1(S1Γ)⊢e2:τaR_1(S_1\Gamma) \vdash e_2 : \tau_a. By induction on e2e_2 with the context S1ΓS_1\Gamma and the substitution R1R_1: W(S1Γ,e2)=(S2,τ2)W(S_1\Gamma, e_2) = (S_2, \tau_2) and R2τ2=τaR_2\tau_2 = \tau_a, with R2S2=R1R_2S_2 = R_1 on each variable not created by the second call.
  3. Each variable of τ1\tau_1 is old for the second call. So R2S2τ1=R1τ1=τa→τ′R_2S_2\tau_1 = R_1\tau_1 = \tau_a \to \tau'. Let R3R_3 be R2R_2 with β:=τ′\beta := \tau', for the fresh β\beta of line L8. The variable β\beta does not occur in S2τ1S_2\tau_1 or τ2\tau_2. So R3S2τ1=τa→τ′R_3S_2\tau_1 = \tau_a \to \tau' and R3(τ2→β)=τa→τ′R_3(\tau_2 \to \beta) = \tau_a \to \tau'.
  4. R3R_3 unifies S2τ1S_2\tau_1 and τ2→β\tau_2 \to \beta. So MGU succeeds at line L8 with S3S_3, and R3=R4S3R_3 = R_4S_3 for some R4R_4.
  5. Take R′=R4R' = R_4. Then R′S3β=R3β=τ′R'S_3\beta = R_3\beta = \tau'. On a variable that the whole call did not create, R4S3S2S1=R3S2S1=R2S2S1=R1S1=RR_4S_3S_2S_1 = R_3S_2S_1 = R_2S_2S_1 = R_1S_1 = R. The second step holds because β\beta does not occur in S2S1αS_2S_1\alpha for an old α\alpha. The third holds because S1αS_1\alpha only has variables that are old for the second call.

Let. The judgment comes from T-Let', so RΓ⊢e1:τaR\Gamma \vdash e_1 : \tau_a and RΓ,x:Gen(RΓ,τa)⊢e2:τ′R\Gamma, x : \mathrm{Gen}(R\Gamma, \tau_a) \vdash e_2 : \tau'.

  1. By induction on e1e_1: W(Γ,e1)=(S1,τ1)W(\Gamma, e_1) = (S_1, \tau_1) with R1τ1=τaR_1\tau_1 = \tau_a and R1S1Γ=RΓR_1S_1\Gamma = R\Gamma.
  2. Claim. R1(Gen(S1Γ,τ1))⊒Gen(RΓ,τa)R_1(\mathrm{Gen}(S_1\Gamma, \tau_1)) \sqsupseteq \mathrm{Gen}(R\Gamma, \tau_a). Let α⃗=ftv(τ1)∖ftv(S1Γ)\vec\alpha = \mathrm{ftv}(\tau_1) \setminus \mathrm{ftv}(S_1\Gamma). Then R1(∀α⃗. τ1)=∀β⃗. R1Pτ1R_1(\forall\vec\alpha.\, \tau_1) = \forall\vec\beta.\, R_1P\tau_1, where P=[α⃗:=β⃗]P = [\vec\alpha := \vec\beta] and β⃗\vec\beta is new. An instance of Gen(RΓ,τa)\mathrm{Gen}(R\Gamma, \tau_a) has the form QR1τ1Q R_1\tau_1, where QQ changes only variables not free in RΓR\Gamma. Let Q′=[β⃗:=QR1α⃗]Q' = [\vec\beta := Q R_1 \vec\alpha]. For a variable δ\delta of τ1\tau_1: if δ∈α⃗\delta \in \vec\alpha, then Q′R1Pδ=QR1δQ'R_1P\delta = QR_1\delta. If not, then δ\delta is free in S1ΓS_1\Gamma, so the variables of R1δR_1\delta are free in R1S1Γ=RΓR_1S_1\Gamma = R\Gamma, and Q′R1Pδ=R1δ=QR1δQ'R_1P\delta = R_1\delta = QR_1\delta. So QR1τ1=Q′(R1Pτ1)QR_1\tau_1 = Q'(R_1P\tau_1) is an instance of R1(∀α⃗. τ1)R_1(\forall\vec\alpha.\, \tau_1).
  3. By the claim and Lemma 1, R1(S1Γ,x:Gen(S1Γ,τ1))⊢e2:τ′R_1(S_1\Gamma, x : \mathrm{Gen}(S_1\Gamma, \tau_1)) \vdash e_2 : \tau'. By induction on e2e_2: W(S1Γ,x:Gen(S1Γ,τ1); e2)=(S2,τ2)W(S_1\Gamma, x : \mathrm{Gen}(S_1\Gamma, \tau_1);\ e_2) = (S_2, \tau_2) with R2τ2=τ′R_2\tau_2 = \tau' and R2S2=R1R_2S_2 = R_1 on variables that the second call did not create.
  4. Take R′=R2R' = R_2. On old variables, R2S2S1=R1S1=RR_2S_2S_1 = R_1S_1 = R, as in the application case. □\square

Principal types and termination

Corollary (principal types). Let ee be closed. If ee has a type, then W(∅,e)=(S,τ)W(\emptyset, e) = (S, \tau), and each type of ee is an instance R′τR'\tau of τ\tau. If ee has no type, W fails.

Proof. If ⊢e:τ′\vdash e : \tau', Theorem 2 with any RR gives τ′=R′τ\tau' = R'\tau. By Theorem 1, ⊢e:τ\vdash e : \tau, and by Lemma 2 each instance of τ\tau is a type of ee. So the types of ee are exactly the instances of τ\tau, and ∀ftv(τ). τ\forall \mathrm{ftv}(\tau).\, \tau is the principal scheme. If W succeeds, Theorem 1 gives a type, so W fails on untypable terms. □\square

Termination. Each call of W recurses on proper subterms, and MGU always stops, so W stops on each input. The number of calls is the number of nodes of ee. The time is not polynomial: see the complexity section of the page.

References

  • Luis Damas and Robin Milner, Principal type-schemes for functional programs, POPL 1982, pages 207 to 212. The statement of soundness and completeness of W.
  • Luis Damas, Type assignment in programming languages, PhD thesis, University of Edinburgh, 1985. The full proofs, and the equivalence of the declarative and the syntax-directed rules.
  • Oukseh Lee and Kwangkeun Yi, Proofs about a folklore let-polymorphic type inference algorithm, ACM TOPLAS 20(4), 1998, pages 707 to 723. Soundness and completeness proofs in the same style for W and for the top-down algorithm M.
  1. Luis Damas and Robin Milner, Principal type-schemes for functional programs, Ninth ACM Symposium on Principles of Programming Languages (POPL 1982), pages 207 to 212, the definition of algorithm W, Theorem 1 (soundness of W) and Theorem 2 (completeness of W), with the principal type-scheme corollary
  2. Robin Milner, A theory of type polymorphism in programming, Journal of Computer and System Sciences 17(3), 1978, pages 348 to 375, Section 4 (algorithm W, its soundness theorem, and the more efficient algorithm J)
  3. Oukseh Lee and Kwangkeun Yi, Proofs about a folklore let-polymorphic type inference algorithm, ACM Transactions on Programming Languages and Systems 20(4), 1998, pages 707 to 723, the soundness and completeness proofs for W and for the top-down algorithm M, and the comparison of where the two algorithms detect a type error
  4. Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, Chapter 22 (constraint typing, unification, principal types, and Section 22.7 on let-polymorphism and its cost)
  5. J. A. Robinson, A machine-oriented logic based on the resolution principle, Journal of the ACM 12(1), 1965, pages 23 to 41, the unification algorithm and the most general unifier, which W calls at each application
  6. A. J. Kfoury, J. Tiuryn and P. Urzyczyn, ML typability is dexptime-complete, CAAP 1990, LNCS 431, Springer, pages 206 to 220, the exponential upper bound for typability with shared types, and the lower bound
  7. David McAllester, A logical algorithm for ML type inference, Rewriting Techniques and Applications (RTA 2003), LNCS 2706, Springer, pages 436 to 451, the nearly linear time bound for programs whose types have bounded order and arity

Complexity

Let nn be the number of nodes of the term. W makes one call per node, but the cost of a call depends on the size of the types.

  • Without let. The term is a simply typed term, and the types are those of Hindley's algorithm. Robinson's unification on trees can build types of exponential size. With shared types, a union-find structure and one test for cycles at the end in place of an occurs check at each step, the time is O(n α(n))O(n\,\alpha(n)).
  • Exponential types. Let $y_0 = $ fun x -> x and $y_i = $ fun z -> z yi−1 yi−1y_{i-1}\ y_{i-1}, nested by let, and return yky_k. The term has 7k+47k + 4 nodes. The principal type has 8⋅2k−58 \cdot 2^k - 5 nodes and 2k+1−12^{k+1} - 1 type variables. Since the output alone is that large, W needs time 2Ω(n)2^{\Omega(n)}, even with sharing.
  • Doubly exponential trees. Let $f_0 = $ fun x -> fun z -> z x x and $f_i = $ fun y -> fi−1 (fi−1 y)f_{i-1}\ (f_{i-1}\ y), nested by let. The term has 7k+97k + 9 nodes. As a tree, the principal type of fkf_k has 6⋅22k−36 \cdot 2^{2^k} - 3 nodes, for example 393,213 nodes at k=4k = 4. As a DAG with shared subtypes it has only 2k+2+22^{k+2} + 2 nodes. So W with types stored as trees takes time 22Ω(n)2^{2^{\Omega(n)}}, and with shared types the cost stays 2O(n)2^{O(n)}.
  • Upper bound. With shared types, W runs in 2O(n)2^{O(n)} time (Kfoury, Tiuryn and Urzyczyn 1990). The typability problem is complete for EXPTIME, and EXPTIME contains problems that are not in polynomial time. So no algorithm for ML typability runs in polynomial time.
  • Bounded nesting. If the nesting depth of let is bounded by a constant, the time is polynomial. McAllester (2003) gives a nearly linear bound when the types have bounded order and arity, which explains why compilers are fast in practice.

A plain implementation also applies each substitution to the whole context at lines L7 and L12. This costs O(∣Γ∣)O(|\Gamma|) per step and O(n2)O(n^2) over the run even for small types. Algorithm J removes this cost.

Properties

  • Principal results. For a closed term, the result type is principal, and it is unique up to renaming of type variables.
  • Deterministic. The result depends only on the input, up to the names of the fresh variables.
  • Error location. W finds an error at the first unification that fails, in a left to right walk. This is often far from the real mistake. Algorithm M finds some errors earlier.
  • Purely functional. W returns substitutions and never changes a shared structure. This makes it easy to prove correct and costly to run.
  • Compositional in one direction. The type of a subterm does not depend on the terms to its right, but it can change when later substitutions are applied.

Variants and improvements

  • Algorithm J. One global substitution in a union-find structure, changed in place. It returns the same types, without the cost of composing and applying substitutions.
  • Levels. Each type variable stores the let depth at which it was made. GEN then quantifies the variables with a deeper level, without a scan of the context. This is Rémy's method, used by OCaml.
  • Algorithm M. Lee and Yi (1998) proved the folklore top-down algorithm correct. It passes the expected type down into the term, and it stops at the first subterm that cannot have the expected type.
  • Constraint-based inference. First generate the equations, then solve them. HM(X) extends this to other constraint domains, such as subtyping or type classes.
  • Value restriction. In a language with mutable references, line L11 quantifies only if e1e_1 is a syntactic value.
  • Bidirectional type checking. Uses written annotations to check richer types, and falls back on W-style inference for the rest.

When to use it

Use W to learn Hindley-Milner inference, to prove facts about it, or in a small interpreter where speed does not matter. Its cases follow the typing rules one by one, so each line has a direct proof. For a compiler, use algorithm J with levels, or constraint-based inference, which compute the same types faster and give better error messages. For languages with first-class polymorphism or subtyping, W alone is not enough.

Pitfalls

  • Generalizing too much. Line L11 must skip the variables that are free in S1ΓS_1\Gamma. If it quantifies them, fun x -> let y = x in if y true then y 1 else 0 gets a type, and the application of it to 5 gets stuck.
  • Using the old context. Line L7 and line L12 must use S1ΓS_1\Gamma, not Γ\Gamma. The scheme in line L11 must also be computed against S1ΓS_1\Gamma: in the old context, a variable that S1S_1 has removed would look free.
  • Leaving out the occurs check. Without it, fun x -> x x gets the cyclic type α=α→β\alpha = \alpha \to \beta, and the program may loop when it prints or applies the substitution.
  • Order of composition. The result substitution is S3S2S1S_3 S_2 S_1, with S1S_1 applied first. Any other order gives wrong types.
  • Believing that W is polynomial. It is not cubic or polynomial. Nested let makes the types exponential, and trees without sharing make them doubly exponential.
  • Polymorphic recursion. Giving ff a scheme in line L14 does not make W infer polymorphic recursion. That problem is undecidable, and languages ask for a type signature instead.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

algorithm_w.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algorithm-w/. The authors are listed in prov/BA10YT.jsonl.
"""Algorithm W of Damas and Milner on the toy lambda language of toylam.py.

W(env, e) returns a pair (S, t): a substitution S and a type t with
S(env) |- e : t. A substitution is a dict from type variable numbers to
types. A type scheme is ("forall", vars, t) with vars a tuple of numbers.
infer(e) returns the principal type of a closed term, or raises TypeErrorHM.
"""

from toylam import normalize_type

INT = ("int",)
BOOL = ("bool",)


class TypeErrorHM(Exception):
    """The term has no type."""


class Fresh:
    """A supply of type variables that were never used before."""

    def __init__(self):
        self.n = 0

    def __call__(self):
        self.n += 1
        return ("tv", self.n - 1)


def fun(a, b):
    return ("fun", a, b)


def apply(s, t):
    """The type t with the substitution s applied."""
    if not s:
        return t
    tag = t[0]
    if tag == "tv":
        return s.get(t[1], t)
    if tag == "fun":
        return ("fun", apply(s, t[1]), apply(s, t[2]))
    return t


def apply_scheme(s, sc):
    bound = sc[1]
    inner = {v: u for v, u in s.items() if v not in bound}
    return ("forall", bound, apply(inner, sc[2]))


def apply_env(s, env):
    if not s:
        return env
    return {x: apply_scheme(s, sc) for x, sc in env.items()}


def compose(s2, s1):
    """The substitution s2 after s1: apply(compose(s2, s1), t) == apply(s2, apply(s1, t))."""
    out = {v: apply(s2, t) for v, t in s1.items()}
    for v, t in s2.items():
        if v not in out:
            out[v] = t
    return out


def ftv(t):
    tag = t[0]
    if tag == "tv":
        return {t[1]}
    if tag == "fun":
        return ftv(t[1]) | ftv(t[2])
    return set()


def ftv_scheme(sc):
    return ftv(sc[2]) - set(sc[1])


def ftv_env(env):
    out = set()
    for sc in env.values():
        out |= ftv_scheme(sc)
    return out


def unify(t1, t2):
    """A most general unifier of t1 and t2 (Robinson), or TypeErrorHM."""
    if t1 == t2:
        return {}
    if t1[0] == "tv":
        return bind(t1[1], t2)
    if t2[0] == "tv":
        return bind(t2[1], t1)
    if t1[0] == "fun" and t2[0] == "fun":
        s1 = unify(t1[1], t2[1])
        s2 = unify(apply(s1, t1[2]), apply(s1, t2[2]))
        return compose(s2, s1)
    raise TypeErrorHM(f"cannot unify {t1} with {t2}")


def bind(v, t):
    if t == ("tv", v):
        return {}
    if v in ftv(t):
        raise TypeErrorHM("occurs check")
    return {v: t}


def instantiate(sc, fresh):
    """Replace the bound variables of the scheme by fresh variables."""
    return apply({v: fresh() for v in sc[1]}, sc[2])


def generalize(env, t):
    """Quantify the variables of t that are not free in env."""
    bound = tuple(sorted(ftv(t) - ftv_env(env)))
    return ("forall", bound, t)


def mono(t):
    return ("forall", (), t)


PRIM_TYPES = {"+": INT, "-": INT, "*": INT, "<": BOOL, "==": BOOL}


def w(env, e, fresh):
    """Algorithm W: returns (S, t) with apply_env(S, env) |- e : t."""
    tag = e[0]
    if tag == "var":  # @line L1
        if e[1] not in env:
            raise TypeErrorHM(f"unbound variable {e[1]}")
        return {}, instantiate(env[e[1]], fresh)  # @line L2
    if tag == "lam":  # @line L3
        a = fresh()
        s1, t1 = w({**env, e[1]: mono(a)}, e[2], fresh)  # @line L4
        return s1, fun(apply(s1, a), t1)  # @line L5
    if tag == "app":  # @line L6
        s1, t1 = w(env, e[1], fresh)
        s2, t2 = w(apply_env(s1, env), e[2], fresh)  # @line L7
        b = fresh()
        s3 = unify(apply(s2, t1), fun(t2, b))  # @line L8
        return compose(s3, compose(s2, s1)), apply(s3, b)  # @line L9
    if tag == "let":  # @line L10
        s1, t1 = w(env, e[2], fresh)
        env1 = apply_env(s1, env)
        sigma = generalize(env1, t1)  # @line L11
        s2, t2 = w({**env1, e[1]: sigma}, e[3], fresh)  # @line L12
        return compose(s2, s1), t2  # @line L13
    if tag == "fix":  # @line L14
        a, b = fresh(), fresh()
        s1, t1 = w({**env, e[1]: mono(fun(a, b)), e[2]: mono(a)}, e[3], fresh)
        s2 = unify(apply(s1, b), t1)  # @line L15
        s = compose(s2, s1)
        return s, apply(s, fun(a, b))
    if tag == "int":
        return {}, INT
    if tag == "bool":
        return {}, BOOL
    if tag == "if":
        s1, t1 = w(env, e[1], fresh)
        s = compose(unify(t1, BOOL), s1)
        s2, t2 = w(apply_env(s, env), e[2], fresh)
        s = compose(s2, s)
        s3, t3 = w(apply_env(s, env), e[3], fresh)
        s = compose(s3, s)
        s4 = unify(apply(s3, t2), t3)
        return compose(s4, s), apply(s4, t3)
    if tag == "prim":
        s1, t1 = w(env, e[2], fresh)
        s = compose(unify(t1, INT), s1)
        s2, t2 = w(apply_env(s, env), e[3], fresh)
        s = compose(s2, s)
        s3 = unify(t2, INT)
        return compose(s3, s), PRIM_TYPES[e[1]]
    raise ValueError(f"not a term: {e!r}")


def infer(e, env=None):
    """The principal type of e, with variables renamed to 0, 1, 2, ... Raises TypeErrorHM."""
    fresh = Fresh()
    s, t = w(dict(env or {}), e, fresh)
    return normalize_type(t)


def principal_type(e):
    """The principal type of the closed term e, or None if e has no type."""
    try:
        return infer(e)
    except TypeErrorHM:
        return None
toylam.py 285 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy lambda language: terms, types, call-by-value small steps.

Terms are tuples:
    ("var", x)              a variable, x is a str
    ("lam", x, e)           fun x -> e
    ("app", e1, e2)         e1 e2
    ("let", x, e1, e2)      let x = e1 in e2
    ("int", k)              an integer constant, k is a Python int
    ("bool", b)             true or false, b is a Python bool
    ("if", e1, e2, e3)      if e1 then e2 else e3
    ("prim", op, e1, e2)    e1 op e2, op is one of + - * < ==
    ("fix", f, x, e)        a recursive function: f is the function itself, x its argument

Types are tuples:
    ("int",)  ("bool",)  ("fun", t1, t2)  ("tv", n)   with n an int

Values are int and bool constants, lambdas and fix terms. The semantics is
call by value, left to right. step(e) returns the next term when e can step,
e itself when e is a value, and the marker "stuck" otherwise. A free
variable, an application of a non-function, a non-boolean condition and an
operator on non-integers are stuck. Substitution only ever puts closed values
into terms, because evaluation starts from closed terms, so no renaming is
needed.
"""

STUCK = "stuck"

PRIMS = ("+", "-", "*", "<", "==")


def is_value(e):
    return e[0] in ("int", "bool", "lam", "fix")


def free_vars(e):
    """The set of free term variables of e."""
    tag = e[0]
    if tag == "var":
        return {e[1]}
    if tag == "lam":
        return free_vars(e[2]) - {e[1]}
    if tag == "app":
        return free_vars(e[1]) | free_vars(e[2])
    if tag == "let":
        return free_vars(e[2]) | (free_vars(e[3]) - {e[1]})
    if tag in ("int", "bool"):
        return set()
    if tag == "if":
        return free_vars(e[1]) | free_vars(e[2]) | free_vars(e[3])
    if tag == "prim":
        return free_vars(e[2]) | free_vars(e[3])
    if tag == "fix":
        return free_vars(e[3]) - {e[1], e[2]}
    raise ValueError(f"not a term: {e!r}")


def subst(e, x, v):
    """Replace the free occurrences of x in e by the closed value v."""
    tag = e[0]
    if tag == "var":
        return v if e[1] == x else e
    if tag == "lam":
        return e if e[1] == x else ("lam", e[1], subst(e[2], x, v))
    if tag == "app":
        return ("app", subst(e[1], x, v), subst(e[2], x, v))
    if tag == "let":
        body = e[3] if e[1] == x else subst(e[3], x, v)
        return ("let", e[1], subst(e[2], x, v), body)
    if tag in ("int", "bool"):
        return e
    if tag == "if":
        return ("if", subst(e[1], x, v), subst(e[2], x, v), subst(e[3], x, v))
    if tag == "prim":
        return ("prim", e[1], subst(e[2], x, v), subst(e[3], x, v))
    if tag == "fix":
        if x in (e[1], e[2]):
            return e
        return ("fix", e[1], e[2], subst(e[3], x, v))
    raise ValueError(f"not a term: {e!r}")


def _prim(op, a, b):
    if op == "+":
        return ("int", a + b)
    if op == "-":
        return ("int", a - b)
    if op == "*":
        return ("int", a * b)
    if op == "<":
        return ("bool", a < b)
    if op == "==":
        return ("bool", a == b)
    raise ValueError(f"unknown operator {op!r}")


def step(e):
    """One call-by-value step: the next term, e itself if e is a value, or STUCK."""
    if is_value(e):
        return e
    tag = e[0]
    if tag == "var":
        return STUCK
    if tag == "app":
        f, a = e[1], e[2]
        if not is_value(f):
            f2 = step(f)
            return STUCK if f2 == STUCK else ("app", f2, a)
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("app", f, a2)
        if f[0] == "lam":
            return subst(f[2], f[1], a)
        if f[0] == "fix":
            return subst(subst(f[3], f[1], f), f[2], a)
        return STUCK
    if tag == "let":
        if not is_value(e[2]):
            e1 = step(e[2])
            return STUCK if e1 == STUCK else ("let", e[1], e1, e[3])
        return subst(e[3], e[1], e[2])
    if tag == "if":
        c = e[1]
        if not is_value(c):
            c2 = step(c)
            return STUCK if c2 == STUCK else ("if", c2, e[2], e[3])
        if c[0] == "bool":
            return e[2] if c[1] else e[3]
        return STUCK
    if tag == "prim":
        a, b = e[2], e[3]
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("prim", e[1], a2, b)
        if not is_value(b):
            b2 = step(b)
            return STUCK if b2 == STUCK else ("prim", e[1], a, b2)
        if a[0] == "int" and b[0] == "int":
            return _prim(e[1], a[1], b[1])
        return STUCK
    raise ValueError(f"not a term: {e!r}")


def evaluate(e, fuel=10000):
    """Run e. Returns ("value", v), ("stuck", t) with the stuck term t, or ("fuel",)."""
    for _ in range(fuel):
        if is_value(e):
            return ("value", e)
        nxt = step(e)
        if nxt == STUCK:
            return ("stuck", e)
        e = nxt
    return ("value", e) if is_value(e) else ("fuel",)


NAMES = ("x", "y", "z", "f", "g")


def random_term(rng, depth, scope=()):
    """A random term of height at most depth whose free variables are in scope.

    With the default empty scope the term is closed. rng is a random.Random.
    """
    scope = tuple(scope)
    if depth <= 0 or rng.random() < 0.15:
        r = rng.random()
        if scope and r < 0.6:
            return ("var", rng.choice(scope))
        if r < 0.8:
            return ("int", rng.randint(0, 3))
        return ("bool", rng.random() < 0.5)
    d = depth - 1
    kind = rng.choice(("var", "lam", "lam", "app", "app", "let", "let", "if", "prim", "fix"))
    if kind == "var" and scope:
        return ("var", rng.choice(scope))
    if kind == "lam" or kind == "var":
        x = rng.choice(NAMES)
        return ("lam", x, random_term(rng, d, scope + (x,)))
    if kind == "app":
        return ("app", random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "let":
        x = rng.choice(NAMES)
        return ("let", x, random_term(rng, d, scope), random_term(rng, d, scope + (x,)))
    if kind == "if":
        return ("if", random_term(rng, d, scope), random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "prim":
        return ("prim", rng.choice(PRIMS), random_term(rng, d, scope), random_term(rng, d, scope))
    f, x = rng.sample(NAMES, 2)
    return ("fix", f, x, random_term(rng, d, scope + (f, x)))


def size(e):
    """The number of nodes of the syntax tree of e."""
    tag = e[0]
    if tag in ("var", "int", "bool"):
        return 1
    if tag == "lam":
        return 1 + size(e[2])
    if tag == "app":
        return 1 + size(e[1]) + size(e[2])
    if tag == "let":
        return 1 + size(e[2]) + size(e[3])
    if tag == "if":
        return 1 + size(e[1]) + size(e[2]) + size(e[3])
    if tag == "prim":
        return 1 + size(e[2]) + size(e[3])
    if tag == "fix":
        return 1 + size(e[3])
    raise ValueError(f"not a term: {e!r}")


def show(e):
    """The surface syntax: fun x -> e, e1 e2, let x = e1 in e2."""
    tag = e[0]
    if tag == "var":
        return e[1]
    if tag == "int":
        return str(e[1])
    if tag == "bool":
        return "true" if e[1] else "false"
    if tag == "lam":
        return f"(fun {e[1]} -> {show(e[2])})"
    if tag == "app":
        return f"({show(e[1])} {show(e[2])})"
    if tag == "let":
        return f"(let {e[1]} = {show(e[2])} in {show(e[3])})"
    if tag == "if":
        return f"(if {show(e[1])} then {show(e[2])} else {show(e[3])})"
    if tag == "prim":
        return f"({show(e[2])} {e[1]} {show(e[3])})"
    if tag == "fix":
        return f"(fix {e[1]} {e[2]} -> {show(e[3])})"
    raise ValueError(f"not a term: {e!r}")


def type_vars(t):
    """The type variables of t, in order of first occurrence, left to right."""
    out = []

    def go(u):
        if u[0] == "tv":
            if u[1] not in out:
                out.append(u[1])
        elif u[0] == "fun":
            go(u[1])
            go(u[2])

    go(t)
    return out


def rename_type(t, mapping):
    if t[0] == "tv":
        return ("tv", mapping.get(t[1], t[1]))
    if t[0] == "fun":
        return ("fun", rename_type(t[1], mapping), rename_type(t[2], mapping))
    return t


def normalize_type(t):
    """Rename the type variables of t to 0, 1, 2, ... in order of first occurrence."""
    return rename_type(t, {v: i for i, v in enumerate(type_vars(t))})


def type_size(t):
    """The number of nodes of t as a tree."""
    if t[0] == "fun":
        return 1 + type_size(t[1]) + type_size(t[2])
    return 1


def show_type(t):
    """int, bool, a, b, ... with right-associative arrows."""
    if t[0] == "int":
        return "int"
    if t[0] == "bool":
        return "bool"
    if t[0] == "tv":
        n = t[1]
        return chr(ord("a") + n) if 0 <= n < 26 else f"t{n}"
    left = show_type(t[1])
    if t[1][0] == "fun":
        left = f"({left})"
    return f"{left} -> {show_type(t[2])}"
test_algorithm_w.py 394 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algorithm-w/. The authors are listed in prov/BA10YT.jsonl.

import random

import pytest

import toylam as L
from algorithm_w import TypeErrorHM, infer, principal_type


def V(x):
    return ("var", x)


def lam(x, e):
    return ("lam", x, e)


def app(a, b):
    return ("app", a, b)


def let(x, a, b):
    return ("let", x, a, b)


I = ("int", 1)
T = ("bool", True)


def parse_type(s):
    """Read a type such as "(a -> b) -> a -> b"; a, b, c, ... are variables 0, 1, 2, ..."""
    toks = s.replace("(", " ( ").replace(")", " ) ").replace("->", " -> ").split()
    pos = [0]

    def atom():
        t = toks[pos[0]]
        pos[0] += 1
        if t == "(":
            r = arrow()
            pos[0] += 1
            return r
        if t in ("int", "bool"):
            return (t,)
        return ("tv", ord(t) - ord("a"))

    def arrow():
        left = atom()
        if pos[0] < len(toks) and toks[pos[0]] == "->":
            pos[0] += 1
            return ("fun", left, arrow())
        return left

    return arrow()


# ---------------------------------------------------------------- the reference check
# The reference does not use W. It expands every let (let x = e1 in e2 becomes
# (fun u -> e2[x := e1]) e1, which also asks e1 to be typable), generates
# the equations of the simply typed rules, and solves them by plain
# unification. A target type is given with rigid variables ("rig", n). Then
# e checks against the target if the equations plus "type of e = target"
# have a solution.


def rename_apart(e, env=None, counter=None):
    """Give every binder a new unique name."""
    env = env or {}
    counter = counter if counter is not None else [0]

    def new(x):
        counter[0] += 1
        return f"{x}_{counter[0]}"

    tag = e[0]
    if tag == "var":
        return ("var", env.get(e[1], e[1]))
    if tag == "lam":
        x = new(e[1])
        return ("lam", x, rename_apart(e[2], {**env, e[1]: x}, counter))
    if tag == "let":
        x = new(e[1])
        return ("let", x, rename_apart(e[2], env, counter), rename_apart(e[3], {**env, e[1]: x}, counter))
    if tag == "fix":
        f, x = new(e[1]), new(e[2])
        return ("fix", f, x, rename_apart(e[3], {**env, e[1]: f, e[2]: x}, counter))
    if tag == "app":
        return ("app", rename_apart(e[1], env, counter), rename_apart(e[2], env, counter))
    if tag == "if":
        return ("if",) + tuple(rename_apart(a, env, counter) for a in e[1:])
    if tag == "prim":
        return ("prim", e[1], rename_apart(e[2], env, counter), rename_apart(e[3], env, counter))
    return e


def open_subst(e, x, r):
    """e[x := r] for a term r with free variables; safe after rename_apart."""
    tag = e[0]
    if tag == "var":
        return r if e[1] == x else e
    if tag == "lam":
        return ("lam", e[1], open_subst(e[2], x, r))
    if tag == "let":
        return ("let", e[1], open_subst(e[2], x, r), open_subst(e[3], x, r))
    if tag == "fix":
        return ("fix", e[1], e[2], open_subst(e[3], x, r))
    if tag == "app":
        return ("app", open_subst(e[1], x, r), open_subst(e[2], x, r))
    if tag == "if":
        return ("if",) + tuple(open_subst(a, x, r) for a in e[1:])
    if tag == "prim":
        return ("prim", e[1], open_subst(e[2], x, r), open_subst(e[3], x, r))
    return e


def expand_lets(e):
    tag = e[0]
    if tag == "let":
        e1, e2 = expand_lets(e[2]), expand_lets(e[3])
        return ("app", ("lam", "_unused", open_subst(e2, e[1], e1)), e1)
    if tag == "lam":
        return ("lam", e[1], expand_lets(e[2]))
    if tag == "fix":
        return ("fix", e[1], e[2], expand_lets(e[3]))
    if tag == "app":
        return ("app", expand_lets(e[1]), expand_lets(e[2]))
    if tag == "if":
        return ("if",) + tuple(expand_lets(a) for a in e[1:])
    if tag == "prim":
        return ("prim", e[1], expand_lets(e[2]), expand_lets(e[3]))
    return e


def equations(e):
    """(t, eqs): the type of the let-free term e and the equations of the simple rules."""
    eqs, n = [], [0]

    def new():
        n[0] += 1
        return ("tv", n[0])

    def go(env, e):
        tag = e[0]
        if tag == "var":
            return env[e[1]]
        if tag == "int":
            return ("int",)
        if tag == "bool":
            return ("bool",)
        if tag == "lam":
            a = new()
            return ("fun", a, go({**env, e[1]: a}, e[2]))
        if tag == "app":
            r = new()
            eqs.append((go(env, e[1]), ("fun", go(env, e[2]), r)))
            return r
        if tag == "fix":
            a, b = new(), new()
            eqs.append((b, go({**env, e[1]: ("fun", a, b), e[2]: a}, e[3])))
            return ("fun", a, b)
        if tag == "if":
            eqs.append((go(env, e[1]), ("bool",)))
            t2 = go(env, e[2])
            eqs.append((t2, go(env, e[3])))
            return t2
        if tag == "prim":
            eqs.append((go(env, e[2]), ("int",)))
            eqs.append((go(env, e[3]), ("int",)))
            return ("int",) if e[1] in "+-*" else ("bool",)
        raise ValueError(tag)

    return go({}, e), eqs


def walk(s, t):
    while t[0] == "tv" and t[1] in s:
        t = s[t[1]]
    return t


def full(s, t):
    t = walk(s, t)
    if t[0] == "fun":
        return ("fun", full(s, t[1]), full(s, t[2]))
    return t


def solve(eqs, s=None):
    """A solution of the equations as a triangular substitution, or None."""
    s = dict(s or {})
    work = list(eqs)
    while work:
        a, b = work.pop()
        a, b = walk(s, a), walk(s, b)
        if a == b:
            continue
        if b[0] == "tv":
            a, b = b, a
        if a[0] == "tv":
            if a[1] in L.type_vars(full(s, b)):
                return None
            s[a[1]] = b
        elif a[0] == "fun" and b[0] == "fun":
            work.append((a[1], b[1]))
            work.append((a[2], b[2]))
        else:
            return None
    return s


class Reference:
    def __init__(self, e):
        if L.free_vars(e):
            self.s = None  # an open term has no type in the empty context
            return
        self.t, eqs = equations(expand_lets(rename_apart(e)))
        self.s = solve(eqs)

    def typable(self):
        return self.s is not None

    def checks(self, target):
        """Does e have the type target? Variables of target are rigid."""
        if self.s is None:
            return False
        return solve([(self.t, rigid(target))], self.s) is not None


def rigid(t):
    if t[0] == "tv":
        return ("rig", t[1])
    if t[0] == "fun":
        return ("fun", rigid(t[1]), rigid(t[2]))
    return t


def is_instance(t, p):
    """Is the type t an instance of the type p? Variables of t are constants."""
    m = {}

    def go(t, p):
        if p[0] == "tv":
            if p[1] in m:
                return m[p[1]] == t
            m[p[1]] = t
            return True
        if p[0] == "fun":
            return t[0] == "fun" and go(t[1], p[1]) and go(t[2], p[2])
        return t == p

    return go(t, p)


def all_types(size):
    """Every type with at most size nodes over int, bool and the variables a, b."""
    by = {1: [("int",), ("bool",), ("tv", 0), ("tv", 1)]}
    for k in range(2, size + 1):
        by[k] = [("fun", x, y) for i in range(1, k - 1) for x in by[i] for y in by[k - 1 - i]]
    return [t for k in by for t in by[k]]


TYPES = all_types(5)


# ---------------------------------------------------------------- tests


@pytest.mark.parametrize(
    "term, expected",
    [
        (lam("x", V("x")), "a -> a"),
        (lam("x", lam("y", V("x"))), "a -> b -> a"),
        (lam("x", lam("y", lam("z", app(app(V("x"), V("z")), app(V("y"), V("z")))))), "(a -> b -> c) -> (a -> b) -> a -> c"),
        (lam("f", lam("g", lam("x", app(V("f"), app(V("g"), V("x")))))), "(a -> b) -> (c -> a) -> c -> b"),
        (let("id", lam("x", V("x")), app(V("id"), V("id"))), "a -> a"),
        (let("id", lam("x", V("x")), ("if", app(V("id"), T), app(V("id"), I), ("int", 0))), "int"),
        (lam("x", let("y", V("x"), V("y"))), "a -> a"),
        (("fix", "f", "n", ("if", ("prim", "<", V("n"), I), I, ("prim", "*", V("n"), app(V("f"), ("prim", "-", V("n"), I))))), "int -> int"),
        (let("k", lam("x", lam("y", V("x"))), app(app(V("k"), V("k")), I)), "a -> b -> a"),
    ],
)
def test_known_principal_types(term, expected):
    assert infer(term) == L.normalize_type(parse_type(expected))


@pytest.mark.parametrize(
    "term",
    [
        lam("x", app(V("x"), V("x"))),
        app(I, I),
        ("if", I, T, T),
        lam("f", ("if", app(V("f"), T), app(V("f"), I), ("int", 0))),
        # y is bound to x, whose type is in the context, so y is not generalized
        lam("x", let("y", V("x"), ("if", app(V("y"), T), app(V("y"), I), ("int", 0)))),
        V("free"),
    ],
)
def test_untypable(term):
    with pytest.raises(TypeErrorHM):
        infer(term)
    assert not Reference(term).typable()


def test_unsound_generalization_would_accept_a_stuck_term():
    # If W generalized over the variable of x, y would get the scheme
    # forall a. a, the function fun x -> let y = x in if y true then y 1 else 0
    # would get the type a -> int, and this application would type check,
    # yet it gets stuck at "5 true".
    bad = lam("x", let("y", V("x"), ("if", app(V("y"), T), app(V("y"), I), ("int", 0))))
    run = app(bad, ("int", 5))
    assert principal_type(bad) is None
    assert principal_type(run) is None
    assert L.evaluate(run)[0] == "stuck"


def random_terms(seed, count, depth):
    rng = random.Random(seed)
    return [L.random_term(rng, rng.randint(1, depth)) for _ in range(count)]


def test_against_brute_force_enumeration_of_types():
    typable = 0
    for e in random_terms(11, 400, 5):
        p = principal_type(e)
        ref = Reference(e)
        assert (p is not None) == ref.typable(), L.show(e)
        if p is None:
            assert not any(ref.checks(t) for t in TYPES)
            continue
        typable += 1
        assert ref.checks(p), L.show(e)
        for t in TYPES:
            assert ref.checks(t) == is_instance(t, p), (L.show(e), L.show_type(p), L.show_type(t))
    assert typable >= 100


def test_typable_terms_do_not_get_stuck():
    for e in random_terms(12, 600, 6):
        p = principal_type(e)
        if p is None:
            continue
        out = L.evaluate(e, 2000)
        assert out[0] != "stuck", L.show(e)
        if out[0] == "value":
            v = out[1]
            if p == ("int",):
                assert v[0] == "int"
            elif p == ("bool",):
                assert v[0] == "bool"
            elif p[0] == "fun":
                assert v[0] in ("lam", "fix")


def nested_let(k):
    """let y0 = fun x -> x in let y1 = fun z -> z y0 y0 in ... in yk"""
    body = V(f"y{k}")
    for i in range(k, 0, -1):
        body = let(f"y{i}", lam("z", app(app(V("z"), V(f"y{i - 1}")), V(f"y{i - 1}"))), body)
    return let("y0", lam("x", V("x")), body)


def test_nested_let_types_grow_exponentially():
    for k in range(0, 11):
        e = nested_let(k)
        assert L.size(e) == 7 * k + 4
        t = infer(e)
        assert L.type_size(t) == 8 * 2**k - 5
        assert len(L.type_vars(t)) == 2 ** (k + 1) - 1
    assert L.show_type(infer(nested_let(1))) == "((a -> a) -> (b -> b) -> c) -> c"


def doubling(k):
    """let f0 = fun x -> fun z -> z x x in let f1 = fun y -> f0 (f0 y) in ... in fk"""
    body = V(f"f{k}")
    for i in range(k, 0, -1):
        body = let(f"f{i}", lam("y", app(V(f"f{i - 1}"), app(V(f"f{i - 1}"), V("y")))), body)
    return let("f0", lam("x", lam("z", app(app(V("z"), V("x")), V("x")))), body)


def test_doubling_family_types_grow_doubly_exponentially_as_trees():
    for k in range(0, 4):
        e = doubling(k)
        assert L.size(e) == 7 * k + 9
        assert L.type_size(infer(e)) == 6 * 2 ** (2**k) - 3
    assert L.show_type(infer(doubling(0))) == "a -> (a -> a -> b) -> b"


def test_principal_type_of_small_family_member_checks():
    e = nested_let(2)
    p = infer(e)
    ref = Reference(e)
    assert ref.checks(p)
    assert not ref.checks(("int",))

History

Hindley (1969) proved that each typable object of combinatory logic has a principal type scheme, and found it with Robinson's unification of 1965. Milner, without knowing Hindley's work, designed the type discipline of ML for the LCF theorem prover. His 1978 paper adds polymorphism at let, defines algorithm W, proves it sound, and gives the faster algorithm J. Damas and Milner (1982) proved that W is complete, so that each typable term has a principal type scheme. The full proofs are in Damas's thesis of 1985. In 1990, Mairson and Kfoury, Tiuryn and Urzyczyn showed that ML typability is complete for exponential time, which ended the belief that W runs in polynomial time. Lee and Yi (1998) proved the folklore top-down algorithm M correct and compared it with W.

References

Where this leads

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 time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example