Algorithmadvanced
Algorithm J
Also called Milner's algorithm J.
An imperative form of Hindley-Milner inference that keeps one global substitution, updated in place by union-find unification.
- Solves
- Type inference problem
- Time
- 2^O(n) worstΘ(n) best
- Space
- 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 J is the fast form of algorithm W for Hindley-Milner type inference. W returns a substitution from each call and composes them. J keeps one global substitution instead, stored in a union-find structure, and changes it in place. Unification links classes of type variables, and a type variable that gets a value points to a shared type node. So types are DAGs, not trees, and a substitution is never applied to the whole context. Milner gave J in his 1978 paper, next to W, as the version to implement. With Rémy's levels for generalization, it is the core of the type checkers of OCaml and many other ML compilers. It returns exactly the principal types that W returns.
In plain words
W keeps writing out new lists of facts, such as "placeholder a is a number", and copies them into every type it knows. J keeps one notice board instead. It pins each fact on the board once, and reads a type by following the pins. Two placeholders that must be equal join one group, so a later fact about one of them is a fact about both.
Because J follows pins instead of making copies, a big type that is used in many places is stored once. For some programs this is the difference between a few dozen boxes and many billions.
J also records how deep inside nested let definitions each placeholder was made. At the end of a definition, the placeholders made inside it that never joined anything outside are free to vary. J finds them from this number, without a search.
The problem
The input and output are those of algorithm W: a context and a term in the language x, fun x -> e, e1 e2, let x = e1 in e2, with constants, if, integer operators and fix f x -> e. J returns a type . The global substitution at the end gives the answer: , and for a closed term is the principal type. If the term has no type, J fails. This is the type inference problem for ML.
The algorithm
Type variables are nodes of a union-find structure. A root variable has no value. A non-root variable points to another variable or to a type node , or . FIND follows the pointers with path compression. Each root has a rank for union by rank and a level, the let depth at which it was made. The global counter depth starts at 0.
J(Γ, e) ▷ E is the global substitution; returns τ with E(Γ) ⊢ e : E(τ)- 1
if e is a variable x then let ∀α1 ... αk. τ be Γ(x) ▷ fail if x is not in Γ - 2
return a copy of τ with α1 ... αk replaced by fresh variables ▷ copy each shared node once - 3
if e is fun x -> e1 then β ← fresh - 4
return β → J((Γ, x : β), e1) - 5
if e is e1 e2 then τ1 ← J(Γ, e1), τ2 ← J(Γ, e2), β ← fresh - 6
UNIFY(τ1, τ2 → β), return β - 7
if e is let x = e1 in e2 then depth ← depth + 1, τ1 ← J(Γ, e1), depth ← depth - 1 - 8
σ ← GEN(τ1), return J((Γ, x : σ), e2) ▷ GEN quantifies the variables of level > depth UNIFY(τ1, τ2)- 9
τ1 ← FIND(τ1), τ2 ← FIND(τ2), if τ1 and τ2 are the same node then return - 10
if both are root variables then link them by rank, and give the root the smaller level - 11
else if one is a root variable v and the other a node t then OCCURS-ADJUST(v, t), point v to t - 12
else if τ1 = a1 → b1 and τ2 = a2 → b2 then UNIFY(a1, a2), UNIFY(b1, b2) - 13
else fail ▷ int against bool, or a base type against an arrow
OCCURS-ADJUST walks the nodes of once, with FIND at each step. It fails if it reaches , which is the occurs check. Otherwise it lowers the level of each root variable of to at most the level of . Both walks in L2 and L11, and the pairs in L12, use a table of the nodes already seen, so each walk is linear in the size of the DAG and not of the tree. fix f x -> e1 makes fresh , types with and , and unifies with the result. if and the operators call UNIFY with , or the other branch.
The classic version of GEN, as in Milner's paper, quantifies the variables of the resolved that are not free in the resolved context. The version with levels gives the same set and costs only a walk over .
Example
Take let id = fun x -> x in id id, with levels.
| step | action | state |
|---|---|---|
| L7 | depth becomes 1, then L3 makes | has level 1, and |
| L7 | depth becomes 0 again | |
| L8 | GEN: has level | |
| L2 | two copies of | and , both at level 0 |
| L5 | fresh | |
| L12 | UNIFY | decompose into two pairs |
| L11 | UNIFY | points to the node |
| L11 | UNIFY: FIND | points to the same node |
The result resolves to , so the type is . The node is shared: and both point to it, and no copy of it was made. W, on the same term, builds the substitution with two copies of the type.
Sharing can save a lot. In the family $f_0 = $ fun x -> fun z -> z x x, $f_i = $ fun y -> , nested by let, the principal type of has nodes in J's DAG, and nodes as a tree. For , that is 130 nodes against 25,769,803,773.
Correctness
Each step of UNIFY is a step of the Martelli-Montanari rules. So if UNIFY starts with the substitution , it ends with , where is a most general unifier of and , or it fails when there is none. Path compression and union by rank change the representation but not the substitution. With this fact, the cases of J perform the same unifications as the cases of W, in the same order, on the context . The soundness and completeness proofs of W then carry over, and J returns the principal type. For levels, two invariants show that a variable of has a level above the current depth exactly when it is not free in the resolved context. The proof file gives the full proof.
Proof: Algorithm J is sound and complete, and computes the same principal types as Wfull
This file proves that algorithm J is sound and complete for the syntax-directed rules of the Hindley-Milner type system, in the same sense as algorithm W. It follows that J and W return the same principal type for each closed term, up to renaming. Then it proves that generalization by levels quantifies exactly the same variables as generalization by a scan of the context. The proof reuses Lemma 1 (a more general context) and Lemma 2 (type substitution) of the proof file of algorithm W, and the correctness of unification by the Martelli-Montanari rules. Like the W proof, it covers the syntax-directed rules. The equivalence with the declarative rules is in the thesis of Damas (1985).
The global substitution
J keeps one union-find structure over type variables. A variable is a root if it has no parent. A non-root variable points to a variable or to a type with or a base type at the top. FIND follows the parents to a root variable or to a non-variable node. The structure has no cycles: L10 links two roots, and L11 links a root to a type in which, by the occurs check, does not occur after FIND.
The structure represents the substitution that maps each variable to the full resolution of : follow FIND, and resolve each child of the node in the same way. Path compression changes the parents but not , because it only replaces a pointer to by a pointer to FIND, which has the same resolution. Union by rank picks which root becomes the child, and both choices represent substitutions that are equal up to a renaming of the two roots. The roots are exactly the variables that maps to themselves, so is idempotent: .
Lemma 3 (unification). Suppose that UNIFY starts with the substitution . If and have no unifier, UNIFY fails. Otherwise it stops with a substitution , where is a most general unifier of and .
Proof. Each step of UNIFY is a step of the Martelli-Montanari rules on the equations for the pairs that are still open. L9 with equal nodes deletes a trivial equation. L12 decomposes an equation between two arrows. L13 is a clash. L10 and L11 eliminate a variable: they bind a root to a node in which does not occur, which composes with . The rules stop, and they fail exactly when there is no unifier. The binding steps compose to a most general unifier (see the Martelli-Montanari page). The memo table of L12 only skips a pair of nodes that this call has already unified. Types are acyclic, so a pair is never inside its own unification, and when it is met again its two sides are already equal.
Soundness and completeness
Write for the substitution when a call starts, and for the substitution when it returns . J never applies to . FIND applies it lazily. The judgment that J ensures is . Fresh variables, and the variables that a call creates, are as in the W proof.
Each call only composes with more bindings, so for a substitution , the change made by the call. For classic generalization, GEN at L8 quantifies the variables of that are not free in . This is . For levels it is the same set, by Lemma 4 below.
Theorem 1 (soundness). If returns and leaves the substitution , then .
Theorem 2 (completeness). If for a substitution , then succeeds with and , and there is a substitution with and for each variable that the call did not create.
Proof of both. The proof is the proof of Theorems 1 and 2 for W, with where is the change of the call. Each case of J makes the same calls in the same order as W on , and makes the same changes.
- Variable (L1, L2). The copy has the bound variables replaced by fresh variables, and it shares the other nodes with the scheme. Its resolution is applied to the resolved scheme body. This is the result of W, with the identity change.
- Abstraction (L3, L4). The context of the inner call is . The result resolves to , which is the result of W.
- Application (L5, L6). The first call has change . The second call starts with , so it sees the context , which is the context of the second call of W. By Lemma 3, UNIFY composes the substitution with an mgu of and . These are the two types of line L8 of W. The total change is , and resolves to .
- Let (L7, L8). After the first call, GEN quantifies the variables of , which is the scheme of W at its line L11. The scheme is stored unresolved in the context, but its free variables resolve with the current , as W applies to the context.
In each case the soundness and completeness arguments of the W proof apply word for word, with in place of the type that W returns.
Corollary (J computes principal types). For a closed term , J succeeds exactly when has a type, and then is a principal type of . So J and W return the same type up to a renaming of type variables.
Proof. As for W: by Theorem 2 each type of is an instance of , and by Theorem 1 and Lemma 2 each instance is a type. Two principal types are instances of each other, so they differ by a renaming.
Levels
In the mode with levels, J keeps a counter depth, the number of let definitions that the current point is inside. A fresh variable gets the current depth as its level. L10 gives the new root the smaller level of the two roots. L11 calls OCCURS-ADJUST, which lowers the level of each variable in to at most the level of . GEN at depth quantifies the variables of with level greater than .
Lemma 4. At L8, at depth , a root variable of has level greater than if and only if is not free in .
Proof. Consider a call at depth . We show two invariants. They hold for each call, by induction on the run.
(A) Each root variable that is free in has a level of at most . When a variable enters the context at L3, its level is the current depth. When a scheme enters at L8, its free variables are free in already. If unification binds a root that is free in to a node , the new free variables of are the variables of , and L11 lowers each of them to the level of , which is at most . If L10 links two roots, the new root gets the smaller level. Levels never go up.
(B) During the call, each root variable that occurs in the resolution of a type the call handles is either free in or was created by the call. The call reads old types only through . Unification keeps this set closed: a binding of a variable that is free in makes the variables of the bound type free in , and a binding of a created variable only adds created or free variables to it.
Now take a root of at L8. If is free in , its level is at most by (A). If is not free in , then by (B) for the inner call it was created by that call, at a depth of at least , so it started with a level greater than . Its level is lowered only by L10 or L11, and only to the level of a variable in the same binding. If that level were at most , the variable would be old for the inner call, and by (B) free in . Then the binding would make free in , or link below a root that is free in . Both contradict the choice of .
So the two modes quantify the same variables, and Theorems 1 and 2 hold for both.
Termination
Each call of J recurses on proper subterms. Each step of UNIFY either stops or links a root, which lowers the number of roots by one, or decomposes a pair of arrow nodes, and each pair is decomposed at most once per call by the memo table. FIND stops because the structure has no cycles. So J stops on each input.
References
- Robin Milner, A theory of type polymorphism in programming, Journal of Computer and System Sciences 17(3), 1978, pages 348 to 375. Section 4 defines J and shows that it computes the same result as W.
- Luis Damas, Type assignment in programming languages, PhD thesis, University of Edinburgh, 1985. The full proofs for W.
- Didier Remy, Extension of ML type system with a sorted equational theory on types, INRIA Research Report 1766, 1992. Generalization by levels and ranked unification.
- 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 J with one global substitution changed by side effects, and the statement that it computes the same result as W)
- Didier Remy, Extension of ML type system with a sorted equational theory on types, INRIA Research Report RR-1766, October 1992, Section 2 (generalization by ranks, now called levels) and Section 3.3 (ranked unification)
- 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 soundness and completeness of W, which J inherits
- Benjamin C. Pierce (ed.), Advanced Topics in Types and Programming Languages, MIT Press, 2005, Chapter 10 by Francois Pottier and Didier Remy, The essence of ML type inference (Section 10.6, efficient constraint solving with a union-find structure, ranks for generalization, and the sharing of types)
- A. J. Kfoury, J. Tiuryn and P. Urzyczyn, ML typability is dexptime-complete, CAAP 1990, LNCS 431, Springer, pages 206 to 220, the exponential time upper bound for typability with types represented as DAGs
Complexity
Let be the number of nodes of the term.
- Without
let. With an occurs check at each binding, as in L11, the time is in the worst case. With one test for cycles at the end in place of the occurs checks, unification on the DAG takes time. - With
let. Each copy at L2 costs time linear in the DAG size of the scheme. The DAG grows by at most its own size at each copy, so the time and the space are . This matches the upper bound of Kfoury, Tiuryn and Urzyczyn (1990). - Lower bound. Typability is complete for EXPTIME, so no algorithm is polynomial. The sharing does not always help: in the family $y_0 = $
fun x -> x, $y_i = $fun z -> z, each use of is a copy with new variables, and the DAG of has nodes. - Generalization. With levels, GEN costs time linear in the DAG of . The classic version also walks the whole context at each
let, which costs perleteven for small types.
Properties
- Same results as W. On each closed term, J and W both fail, or both return the principal type, up to renaming.
- Imperative. J changes a global structure. A type that J returned earlier can change its meaning when a later unification links one of its variables. So J must always read types through FIND.
- Shared types. Copies are made only at L2, and only of the quantified part. The result is a DAG.
- Not backtracking. A failed unification leaves the structure half changed. A compiler that reports an error and goes on must undo the changes or start again.
Variants and improvements
- Levels (Rémy 1992). The version above. It replaces the scan of the context by a level check, and OCaml uses it.
- Occurs check at the end. Skip the check in L11, and look for cycles only before GEN and at the end. This gives the near-linear bound for terms without
let. With recursive types, cycles are allowed and the check goes away. - Constraint-based inference. Pottier and Rémy's solver for HM(X) works on the same union-find structure with ranks, but it first builds a constraint and then solves it.
- Algorithm W. The functional version, easier to prove correct and slower to run.
When to use it
Use J, with levels, whenever you implement Hindley-Milner inference for real programs. It is the standard design in compilers of ML-family languages. Use W instead when you want a short, pure program that follows the proofs, or when you need to keep the old states, for example in a type checker that tries several branches.
Pitfalls
- Reading a type without FIND. A type node may contain a variable that now points elsewhere. Each walk must call FIND at each node, as in L9 and in OCCURS-ADJUST.
- Copying shared nodes more than once. A copy at L2, or a walk in OCCURS-ADJUST, that does not keep a table of seen nodes treats the DAG as a tree. Then it takes doubly exponential time on the family above.
- Wrong levels. If L10 keeps the larger level, or L11 does not lower the levels of , GEN quantifies a variable that is still free in the context. Then
fun x -> let y = x in if y true then y 1 else 0gets a type, and its application to5gets stuck. - Forgetting to restore the depth. L7 must lower the depth after typing , also when fails and the error is caught.
- Equality of nodes. L9 compares nodes, not the trees they stand for. A structural comparison of two big DAGs can take exponential time.
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-j/. The authors are listed in prov/M228A9.jsonl.
"""Algorithm J of Milner on the toy lambda language of toylam.py.
J keeps one global substitution E in a union-find structure. A type
variable ("tv", n) is either a root (no entry in parent) or points to a
type in parent. find follows these links with path compression. Unification
links roots in place, with union by rank between two variables, so J never
builds or composes substitutions.
Generalization has two modes. With levels=False, J quantifies the variables
of the resolved type that are not free in the resolved environment, as in
Milner's paper. With levels=True, every variable carries the let depth at
which it was made, unification lowers levels, and J quantifies the
variables whose level is deeper than the current one (Remy's method). Both
give the same types.
"""
from toylam import normalize_type
INT = ("int",)
BOOL = ("bool",)
PRIM_TYPES = {"+": INT, "-": INT, "*": INT, "<": BOOL, "==": BOOL}
class TypeErrorHM(Exception):
"""The term has no type."""
class J:
def __init__(self, levels=False):
self.levels = levels
self.parent = {} # variable number -> the type it is linked to
self.rank = {}
self.level = {}
self.depth = 0 # the let depth of the current point
self.count = 0
self.unions = 0 # links made by unification
def new(self):
n = self.count
self.count += 1
self.rank[n] = 0
self.level[n] = self.depth
return ("tv", n)
def find(self, t):
"""The representative of t: a root variable or a type with a constructor on top."""
path = []
while t[0] == "tv" and t[1] in self.parent:
path.append(t[1])
t = self.parent[t[1]]
for v in path[:-1]:
self.parent[v] = t # path compression
return t
def occurs_adjust(self, v, t, seen=None):
"""Fail if v occurs in t. Lower the levels of the variables of t to the level of v.
seen holds the shared nodes already visited, so the walk is linear in the size of the DAG.
"""
if seen is None:
seen = {}
t = self.find(t)
if t[0] == "tv":
if t[1] == v:
raise TypeErrorHM("occurs check")
if self.level[t[1]] > self.level[v]:
self.level[t[1]] = self.level[v]
elif t[0] == "fun" and id(t) not in seen:
seen[id(t)] = t
self.occurs_adjust(v, t[1], seen)
self.occurs_adjust(v, t[2], seen)
def unify(self, t1, t2, done=None):
"""Make t1 and t2 equal in the global substitution, or raise TypeErrorHM.
done holds the pairs of shared nodes already unified in this call.
"""
if done is None:
done = {}
t1, t2 = self.find(t1), self.find(t2) # @line L9
if t1 is t2 or (t1[0] != "fun" and t1 == t2):
return
if t1[0] == "tv" and t2[0] == "tv": # @line L10
a, b = t1[1], t2[1]
if self.rank[a] > self.rank[b]:
a, b = b, a
self.parent[a] = ("tv", b) # union by rank
if self.rank[a] == self.rank[b]:
self.rank[b] += 1
self.level[b] = min(self.level[a], self.level[b])
self.unions += 1
return
if t2[0] == "tv":
t1, t2 = t2, t1
if t1[0] == "tv": # @line L11
self.occurs_adjust(t1[1], t2)
self.parent[t1[1]] = t2
self.unions += 1
return
if t1[0] == "fun" and t2[0] == "fun": # @line L12
key = (id(t1), id(t2))
if key in done:
return
done[key] = (t1, t2)
self.unify(t1[1], t2[1], done)
self.unify(t1[2], t2[2], done)
return
raise TypeErrorHM(f"cannot unify {t1[0]} with {t2[0]}") # @line L13
def resolve(self, t):
"""The type t with the global substitution applied in full."""
t = self.find(t)
if t[0] == "fun":
return ("fun", self.resolve(t[1]), self.resolve(t[2]))
return t
def free_vars(self, t, out, seen=None):
if seen is None:
seen = {}
t = self.find(t)
if t[0] == "tv":
out.add(t[1])
elif t[0] == "fun" and id(t) not in seen:
seen[id(t)] = t
self.free_vars(t[1], out, seen)
self.free_vars(t[2], out, seen)
def generalize(self, env, t):
if self.levels:
vs = set()
self.free_vars(t, vs)
bound = tuple(sorted(v for v in vs if self.level[v] > self.depth))
else:
vs, envs = set(), set()
self.free_vars(t, vs)
for sc in env.values():
fv = set()
self.free_vars(sc[2], fv)
envs |= fv - set(sc[1])
bound = tuple(sorted(vs - envs))
return ("forall", bound, t)
def instantiate(self, sc):
if not sc[1]:
return sc[2]
m = {v: self.new() for v in sc[1]}
memo = {} # shared nodes are copied once, so the copy is a DAG of the same size
def copy(t):
t = self.find(t)
if t[0] == "tv":
return m.get(t[1], t)
if t[0] == "fun":
hit = memo.get(id(t))
if hit is not None:
return hit[1]
c = ("fun", copy(t[1]), copy(t[2]))
memo[id(t)] = (t, c)
return c
return t
return copy(sc[2])
def j(self, env, e):
"""Algorithm J: returns t; E(env) |- e : E(t) for the global E after the call."""
tag = e[0]
if tag == "var": # @line L1
if e[1] not in env:
raise TypeErrorHM(f"unbound variable {e[1]}")
return self.instantiate(env[e[1]]) # @line L2
if tag == "lam": # @line L3
a = self.new()
t1 = self.j({**env, e[1]: ("forall", (), a)}, e[2])
return ("fun", a, t1) # @line L4
if tag == "app": # @line L5
t1 = self.j(env, e[1])
t2 = self.j(env, e[2])
b = self.new()
self.unify(t1, ("fun", t2, b)) # @line L6
return b
if tag == "let": # @line L7
self.depth += 1
t1 = self.j(env, e[2])
self.depth -= 1
sigma = self.generalize(env, t1) # @line L8
return self.j({**env, e[1]: sigma}, e[3])
if tag == "fix":
a, b = self.new(), self.new()
t1 = self.j({**env, e[1]: ("forall", (), ("fun", a, b)), e[2]: ("forall", (), a)}, e[3])
self.unify(b, t1)
return ("fun", a, b)
if tag == "int":
return INT
if tag == "bool":
return BOOL
if tag == "if":
self.unify(self.j(env, e[1]), BOOL)
t2 = self.j(env, e[2])
t3 = self.j(env, e[3])
self.unify(t2, t3)
return t2
if tag == "prim":
self.unify(self.j(env, e[2]), INT)
self.unify(self.j(env, e[3]), INT)
return PRIM_TYPES[e[1]]
raise ValueError(f"not a term: {e!r}")
def infer(e, levels=False):
"""The principal type of the closed term e, renamed to 0, 1, 2, ... Raises TypeErrorHM."""
st = J(levels)
t = st.j({}, e)
return normalize_type(st.resolve(t))
def principal_type(e, levels=False):
"""The principal type of e, or None if e has no type."""
try:
return infer(e, levels)
except TypeErrorHM:
return None
def dag_size(e, levels=True):
"""The number of distinct nodes of the principal type of e in J's shared representation."""
st = J(levels)
t = st.j({}, e)
seen = set()
def walk(u):
u = st.find(u)
key = id(u) if u[0] == "fun" else u
if key in seen:
return
seen.add(key)
if u[0] == "fun":
walk(u[1])
walk(u[2])
walk(t)
return len(seen)
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_j.py 372 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algorithm-j/. The authors are listed in prov/M228A9.jsonl.
import random
import pytest
import toylam as L
from algorithm_j import J, TypeErrorHM, dag_size, 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)
INT, BOOL = ("int",), ("bool",)
OPS = {"+": INT, "-": INT, "*": INT, "<": BOOL, "==": BOOL}
# ---------------------------------------------------------------- a small algorithm W
# W with explicit substitutions, written apart from J, to compare the two.
def apply(s, t):
if t[0] == "tv":
return apply(s, s[t[1]]) if t[1] in s else t
if t[0] == "fun":
return ("fun", apply(s, t[1]), apply(s, t[2]))
return t
def unify_w(s, a, b):
a, b = apply(s, a), apply(s, b)
if a == b:
return
if b[0] == "tv":
a, b = b, a
if a[0] == "tv":
if a[1] in L.type_vars(b):
raise TypeErrorHM("occurs")
s[a[1]] = b
elif a[0] == "fun" and b[0] == "fun":
unify_w(s, a[1], b[1])
unify_w(s, a[2], b[2])
else:
raise TypeErrorHM("clash")
def reference_w(e):
s, n = {}, [0]
def new():
n[0] += 1
return ("tv", n[0])
def env_vars(env):
out = set()
for bound, t in env.values():
out |= set(L.type_vars(apply(s, t))) - set(bound)
return out
def go(env, e):
tag = e[0]
if tag == "var":
if e[1] not in env:
raise TypeErrorHM("unbound")
bound, t = env[e[1]]
m = {v: new() for v in bound}
return L.rename_type(apply(s, t), {}) if not m else apply(m, apply(s, t))
if tag == "lam":
a = new()
return ("fun", a, go({**env, e[1]: ((), a)}, e[2]))
if tag == "app":
t1, t2, b = go(env, e[1]), go(env, e[2]), new()
unify_w(s, t1, ("fun", t2, b))
return b
if tag == "let":
t1 = apply(s, go(env, e[2]))
bound = tuple(v for v in L.type_vars(t1) if v not in env_vars(env))
return go({**env, e[1]: (bound, t1)}, e[3])
if tag == "fix":
a, b = new(), new()
unify_w(s, b, go({**env, e[1]: ((), ("fun", a, b)), e[2]: ((), a)}, e[3]))
return ("fun", a, b)
if tag == "int":
return INT
if tag == "bool":
return BOOL
if tag == "if":
unify_w(s, go(env, e[1]), BOOL)
t2, t3 = go(env, e[2]), go(env, e[3])
unify_w(s, t2, t3)
return t2
if tag == "prim":
unify_w(s, go(env, e[2]), INT)
unify_w(s, go(env, e[3]), INT)
return OPS[e[1]]
raise ValueError(tag)
try:
return L.normalize_type(apply(s, go({}, e)))
except TypeErrorHM:
return None
# ---------------------------------------------------------------- the brute-force check
# let x = e1 in e2 becomes (fun u -> e2[x := e1]) e1, then the simple rules
# give equations, solved by plain unification. A target type has rigid
# variables ("rig", n). The term checks against the target if the equations
# plus "type of e = target" have a solution. No let and no J is involved.
def rename_apart(e, env, counter):
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 expand(e, sub):
"""Expand every let; sub maps let-bound names to their expanded definitions."""
tag = e[0]
if tag == "var":
return sub.get(e[1], e)
if tag == "let":
e1 = expand(e[2], sub)
return ("app", ("lam", "_unused", expand(e[3], {**sub, e[1]: e1})), e1)
if tag == "lam":
return ("lam", e[1], expand(e[2], sub))
if tag == "fix":
return ("fix", e[1], e[2], expand(e[3], sub))
if tag == "app":
return ("app", expand(e[1], sub), expand(e[2], sub))
if tag == "if":
return ("if",) + tuple(expand(a, sub) for a in e[1:])
if tag == "prim":
return ("prim", e[1], expand(e[2], sub), expand(e[3], sub))
return e
def equations(e):
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 in ("int", "bool"):
return (tag,)
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
eqs.append((go(env, e[2]), INT))
eqs.append((go(env, e[3]), INT))
return OPS[e[1]]
return go({}, e), eqs
def solve(eqs, s):
s = dict(s)
s_ok = {}
try:
for a, b in eqs:
unify_w(s, a, b)
except TypeErrorHM:
return None
s_ok.update(s)
return s_ok
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
class Reference:
def __init__(self, e):
self.s = None
if not L.free_vars(e):
self.t, eqs = equations(expand(rename_apart(e, {}, [0]), {}))
self.s = solve(eqs, {})
def checks(self, target):
return self.s is not None and solve([(self.t, rigid(target))], self.s) is not None
def is_instance(t, p):
m = {}
def go(t, p):
if p[0] == "tv":
return m.setdefault(p[1], t) == t
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):
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)
def random_terms(seed, count, depth):
rng = random.Random(seed)
return [L.random_term(rng, rng.randint(1, depth)) for _ in range(count)]
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 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)
# ---------------------------------------------------------------- tests
@pytest.mark.parametrize("levels", [False, True])
def test_known_types(levels):
S = lam("x", lam("y", lam("z", app(app(V("x"), V("z")), app(V("y"), V("z"))))))
assert L.show_type(infer(S, levels)) == "(a -> b -> c) -> (a -> b) -> a -> c"
assert L.show_type(infer(let("id", lam("x", V("x")), app(V("id"), V("id"))), levels)) == "a -> a"
assert L.show_type(infer(lam("x", let("y", V("x"), V("y"))), levels)) == "a -> a"
two_uses = let("id", lam("x", V("x")), ("if", app(V("id"), T), app(V("id"), I), ("int", 0)))
assert infer(two_uses, levels) == INT
@pytest.mark.parametrize("levels", [False, True])
@pytest.mark.parametrize(
"term",
[
lam("x", app(V("x"), V("x"))),
app(I, I),
lam("f", ("if", app(V("f"), T), app(V("f"), I), ("int", 0))),
lam("x", let("y", V("x"), ("if", app(V("y"), T), app(V("y"), I), ("int", 0)))),
V("free"),
],
)
def test_untypable(term, levels):
with pytest.raises(TypeErrorHM):
infer(term, levels)
def test_j_w_and_levels_agree_on_random_terms():
seen = {True: 0, False: 0}
for e in random_terms(21, 1500, 6):
w = reference_w(e)
assert principal_type(e) == w, L.show(e)
assert principal_type(e, True) == w, L.show(e)
seen[w is not None] += 1
assert seen[True] >= 400 and seen[False] >= 400
def test_against_brute_force_enumeration_of_types():
typable = 0
for e in random_terms(22, 300, 5):
p = principal_type(e, True)
ref = Reference(e)
assert (p is not None) == (ref.s is not None), L.show(e)
if p is None:
assert not any(ref.checks(t) for t in TYPES)
continue
typable += 1
for t in TYPES:
assert ref.checks(t) == is_instance(t, p), (L.show(e), L.show_type(t))
assert typable >= 80
def test_typable_terms_do_not_get_stuck():
for e in random_terms(23, 600, 6):
if principal_type(e, True) is not None:
assert L.evaluate(e, 2000)[0] != "stuck", L.show(e)
def test_nested_let_tree_and_dag_sizes():
for k in range(0, 9):
e = nested_let(k)
t = infer(e, True)
assert L.type_size(t) == 8 * 2**k - 5
assert t == reference_w(e)
# the copies made at each use of y(i-1) have new variables, so sharing
# does not help here: the DAG is exponential too
assert dag_size(e) == 6 * 2**k - 4
def test_doubling_family_is_small_as_a_dag_and_huge_as_a_tree():
for k in range(0, 8):
e = doubling(k)
assert L.size(e) == 7 * k + 9
assert dag_size(e) == 2 ** (k + 2) + 2
sizes = [L.type_size(infer(doubling(k), True)) for k in range(3)]
assert sizes == [9, 21, 93]
def test_union_by_rank_and_path_compression_keep_finds_short():
st = J(levels=True)
vs = [st.new() for _ in range(64)]
for i in range(0, 64, 1):
st.unify(vs[0], vs[i])
assert max(st.rank.values()) <= 6
root = st.find(vs[63])
assert all(st.find(v) == root for v in vs)
History
Milner (1978) presented algorithm W for the proofs and algorithm J for the implementation of ML in the LCF system. He showed that J computes the same result as W, with one global substitution changed by side effects. Rémy's work on records, around 1989 to 1992, introduced ranks of type variables for fast generalization. These ranks, now called levels, are what the OCaml type checker uses. Pottier and Rémy (2005) described a constraint solver for ML type inference with the same data structures.
References
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 M228A9 Edit this page History Report an error Markdown