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.
- Solves
- Type inference problem
- Time
- 2^(2^O(n)) worstΘ(n) best
- Space
- 2^(2^O(n)) extra
- Where
- n = the number of nodes of the term
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
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 that maps term variables to type schemes, and a term 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 and a type with in the Hindley-Milner rules, such that each other solution is an instance of . If no substitution and type give , the output is a failure. For a closed term, is empty and is the principal type. This is the type inference problem for ML.
The algorithm
A substitution maps type variables to types. means "first , then ". A variable is fresh if it was never used before. is the scheme , where are the variables of that are not free in . MGU is a most general unifier with the occurs check, for example Robinson's algorithm.
W(Γ, e) ▷ returns (S, τ) with SΓ ⊢ e : τ, or fails- 1
if e is a variable x then let ∀α1 ... αk. τ be Γ(x) ▷ fail if x is not in Γ - 2
return (id, [α1 := β1, ..., αk := βk] τ) ▷ β1 ... βk fresh - 3
if e is fun x -> e1 then β ← fresh - 4
(S1, τ1) ← W((Γ, x : β), e1) - 5
return (S1, S1 β → τ1) - 6
if e is e1 e2 then (S1, τ1) ← W(Γ, e1) - 7
(S2, τ2) ← W(S1 Γ, e2) - 8
β ← fresh, S3 ← MGU(S2 τ1, τ2 → β) ▷ fail if there is no unifier - 9
return (S3 S2 S1, S3 β) - 10
if e is let x = e1 in e2 then (S1, τ1) ← W(Γ, e1) - 11
σ ← GEN(S1 Γ, τ1) ▷ only variables not free in S1 Γ - 12
(S2, τ2) ← W((S1 Γ, x : σ), e2) - 13
return (S2 S1, τ2) - 14
if e is fix f x -> e1 then α, β ← fresh, (S1, τ1) ← W((Γ, f : α → β, x : α), e1) - 15
S2 ← 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 , the operands with and the two branches with each other. Note that and 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 for the fresh variables in the order W makes them.
| step | call | result |
|---|---|---|
| L10 | W(∅, fun x -> x) |
L3 makes . The body x gives , so the result is |
| L11 | GEN(∅, ) | , since the context is empty |
| L6 | W(id : σ, id) |
a fresh copy |
| L7 | W(id : σ, id) |
another fresh copy |
| L8 | MGU(, ) | |
| L9 | the type |
The principal type is . The two uses of id got different instances, and , which is possible only because line L11 quantified .
Now take fun x -> let y = x in if y true then y 1 else 0. Line L3 gives x the type . At line L11 the context is , so is free in it and GEN returns with no quantifier. Then y true unifies with , and y 1 must unify with , 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 , then . Completeness: if for some substitution , then W succeeds with , and and for some . Both are proved by induction on . Soundness needs the type substitution lemma: if , then . That lemma holds only because GEN skips the variables that are free in the context. Completeness needs the fact that for any unifier 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 maps type variables to types and is the identity on all but finitely many. acts on a type by replacing each variable at once. On a scheme , we first rename to variables that does not touch and that do not occur in the range of , and then apply to the body. is the composition: first , then . Schemes are equal up to renaming of bound variables and removal of bound variables that do not occur in the body.
A scheme is more general than , written , if each instance of is an instance of . Contexts are compared name by name.
W returns a pair or fails. It calls MGU, the most general unifier of Robinson's algorithm. We use two facts about MGU. If MGU returns , then . If some has , then MGU succeeds and returns a with for some . The variables in all occur in or (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 creates the fresh variables that it and its nested calls take. Each variable in the result is free in 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 and , then .
Proof. First, . Write . Rename the bound variables of to variables that do not occur in , so that . The body is an instance of , so for an that changes only . A free variable of occurs in , and , so occurs in . It is not in , so .
Now use induction on the derivation, for all contexts in which some names have more general schemes. At T-Var', an instance of is an instance of . 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.
Lemma 2 (type substitution). If , then for each substitution , by a derivation of the same height.
Proof. Induction on the height of the derivation, for all at once. T-Abs and T-App follow from the induction hypothesis. At T-Var', and . Rename so that does not touch these variables and they do not occur in the range of . Then , and is an instance of it.
At T-Let', the premises are and , where . Choose new variables that do not occur in , or , and let . By the induction hypothesis with , . Since is not free in , . The variables are not free in , so quantifies all of and is more general than , which is . By the induction hypothesis with on the second premise, . By Lemma 1, the same holds with . T-Let' gives . Lemma 1 does not increase the height, so the heights stay the same.
The side condition of generalization is used in the step . If also quantified variables that are free in , this step and Lemma 2 would fail, and so would soundness.
Soundness
Theorem 1 (soundness). If , then .
Proof. Induction on .
- Variable (lines L1 and L2). , is the identity, and is an instance. T-Var' applies.
- Abstraction (lines L3 to L5). By induction, . T-Abs gives .
- Application (lines L6 to L9). By induction, and . By Lemma 2 with and with , and . Line L8 gives . T-App gives the type .
- Let (lines L10 to L13). By induction, and with . Exactly as in the
letcase of Lemma 2, with in place of and in place of , there is a type with and . Lemma 1 and T-Let' give .
Completeness
Theorem 2 (completeness). Let be a substitution with . Then succeeds with a result , and there is a substitution with and for each variable that the call did not create.
Proof. Induction on , for all , and . The variables created by the call are fresh, so they do not occur in , and we may change on them freely.
Variable. Let , with apart from . The judgment comes from T-Var', so for some types . W returns with fresh . Let be with . Then , and on each old variable.
Abstraction. The judgment comes from T-Abs, so and . Let be with , for the fresh of line L3. Then . By induction, with an such that and on the variables not created by that call. In particular . So . Take .
Application. The judgment comes from T-App, so and .
- By induction on : and , with on old variables. So .
- So . By induction on with the context and the substitution : and , with on each variable not created by the second call.
- Each variable of is old for the second call. So . Let be with , for the fresh of line L8. The variable does not occur in or . So and .
- unifies and . So MGU succeeds at line L8 with , and for some .
- Take . Then . On a variable that the whole call did not create, . The second step holds because does not occur in for an old . The third holds because only has variables that are old for the second call.
Let. The judgment comes from T-Let', so and .
- By induction on : with and .
- Claim. . Let . Then , where and is new. An instance of has the form , where changes only variables not free in . Let . For a variable of : if , then . If not, then is free in , so the variables of are free in , and . So is an instance of .
- By the claim and Lemma 1, . By induction on : with and on variables that the second call did not create.
- Take . On old variables, , as in the application case.
Principal types and termination
Corollary (principal types). Let be closed. If has a type, then , and each type of is an instance of . If has no type, W fails.
Proof. If , Theorem 2 with any gives . By Theorem 1, , and by Lemma 2 each instance of is a type of . So the types of are exactly the instances of , and is the principal scheme. If W succeeds, Theorem 1 gives a type, so W fails on untypable terms.
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 . 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.
- 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
- 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)
- 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
- 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)
- 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
- 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
- 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 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 . - Exponential types. Let $y_0 = $
fun x -> xand $y_i = $fun z -> z, nested bylet, and return . The term has nodes. The principal type has nodes and type variables. Since the output alone is that large, W needs time , even with sharing. - Doubly exponential trees. Let $f_0 = $
fun x -> fun z -> z x xand $f_i = $fun y ->, nested bylet. The term has nodes. As a tree, the principal type of has nodes, for example 393,213 nodes at . As a DAG with shared subtypes it has only nodes. So W with types stored as trees takes time , and with shared types the cost stays . - Upper bound. With shared types, W runs in 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
letis 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 per step and 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
letdepth 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 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 . If it quantifies them,
fun x -> let y = x in if y true then y 1 else 0gets a type, and the application of it to5gets stuck. - Using the old context. Line L7 and line L12 must use , not . The scheme in line L11 must also be computed against : in the old context, a variable that has removed would look free.
- Leaving out the occurs check. Without it,
fun x -> x xgets the cyclic type , and the program may loop when it prints or applies the substitution. - Order of composition. The result substitution is , with applied first. Any other order gives wrong types.
- Believing that W is polynomial. It is not cubic or polynomial. Nested
letmakes the types exponential, and trees without sharing make them doubly exponential. - Polymorphic recursion. Giving 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.
# 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BA10YT Edit this page History Report an error Markdown