Principal Types for a Tiny Lambda Calculus
Trees & GraphsModel answerLast updated
Build an AST for variables, lambdas and applications, then infer each expression's most general function type using unification, with an occurs check to reject infinite types.
Task
You are building the type checker for a very small functional language. Programs are trees made of three node kinds:
Var(name)is a reference to a variable.Abs(param, body)is a one-argument function (a lambda) that bindsparaminsidebody.App(fn, arg)callsfnwitharg.
There are no literals, no let, and no built-in types. The only types are unknown type variables and function types.
Write a class TypeInferencer with a method infer(expr) -> str. It must return the most general (principal) type of expr as a string, or raise UnificationError if the expression cannot be typed.
Output format
- Type variables are written
T0,T1,T2, and so on. They are numbered in the order they first appear when reading the final string from left to right, regardless of how many temporary variables you created internally. - A function type from
AtoBis written(A -> B). Every arrow gets its own pair of parentheses, so nesting looks like(T0 -> (T1 -> T0)).
Examples
| Expression | Result |
|---|---|
Abs("x", Var("x")) | "(T0 -> T0)" |
Abs("x", App(Var("x"), Var("x"))) | raises UnificationError (it would need an infinite type) |
Abs("f", Abs("x", App(Var("f"), Var("x")))) | "((T0 -> T1) -> (T0 -> T1))" |
Abs("x", Abs("x", Var("x"))) | "(T0 -> (T1 -> T1))" |
Rules and constraints
- Input expressions are finite trees.
- Scoping is lexical. An inner binder with the same name shadows the outer one only inside its own body.
- A variable that is not bound by any enclosing
Absmust raise a separateUnboundVariableError, so that callers can tell it apart from a type conflict. - Calling
inferseveral times on the same object must give deterministic results, so each call has to start with fresh numbering.
What to deliver
Explain your approach, give the data structures for the AST and for types, implement infer, and state the time and space complexity. Be ready to explain why self-application fails and how you would extend the system with polymorphic let.
Hints
Hint 1
Treat inference as constraint solving. Give every lambda parameter a brand-new unknown type, and let the rules for each node tell you which unknowns must be equal.
Hint 2
For an application, infer the types of the function and the argument, invent a fresh unknown for the result, and demand that the function's type equals 'argument type -> result'. Making two types equal is exactly what unification does.
Hint 3
Before binding a type variable to a type, check that the variable does not occur inside that type. Skipping this check lets x x slip through with a cyclic type. Also rename variables only when printing, in order of first appearance.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is classic Hindley-Milner inference (Algorithm W) restricted to the lambda calculus without let. It has three parts: a type representation, a recursive walk over the AST that generates and immediately solves equality constraints, and a unifier with an occurs check.
1. Representation
- A type is either a type variable or an arrow holding a domain type and a codomain type.
- Each type variable carries a mutable
linkfield. When unification decides that a variable equals some type, we store that type inlink. Following links to the end is a union-find "find", and we compress paths as we go. This means we never have to pass a substitution map around: the solved state lives inside the type graph. - The environment is an immutable-style mapping from program variable names to types. Extending it makes a copy, so an inner binder shadows an outer one only within its body, and no renaming pass is needed.
2. Walking the tree
Var(x): lookxup in the environment. If it is missing, raiseUnboundVariableError.Abs(x, body): create a fresh variableaforx, inferbodyin the environment extended withx : a, and return the arrowa -> type(body).App(f, v): infer both sides, create a fresh result variabler, unify the function's type withtype(v) -> r, and returnr.
3. Unification
Resolve both sides to their representatives first, then:
- Same node: done.
- One side is a variable: run the occurs check (does the variable appear inside the other type?). If it does, raise
UnificationError. Otherwise set the variable's link to the other type. - Both are arrows: unify the domains, then the codomains.
Binding only when forced, and only to what is required, yields the most general unifier, so the final type is principal.
4. Printing
Walk the resolved type left to right. The first time an unresolved variable is seen, assign it the next name T0, T1, and so on, and reuse that name for later occurrences. Wrap every arrow in parentheses. Because naming happens only here, the output does not depend on how many temporaries were allocated.
Code
from dataclasses import dataclass
@dataclass(frozen=True)
class Var:
name: str
@dataclass(frozen=True)
class Abs:
param: str
body: object
@dataclass(frozen=True)
class App:
fn: object
arg: object
class UnificationError(Exception):
pass
class UnboundVariableError(Exception):
pass
class _TV:
__slots__ = ("uid", "link")
def __init__(self, uid):
self.uid = uid
self.link = None
class _Fn:
__slots__ = ("dom", "cod")
def __init__(self, dom, cod):
self.dom, self.cod = dom, cod
class TypeInferencer:
def infer(self, expr) -> str:
self._next = 0
ty = self._walk(expr, {})
return self._show(ty, {})
def _new(self):
v = _TV(self._next)
self._next += 1
return v
def _find(self, t):
if isinstance(t, _TV) and t.link is not None:
t.link = self._find(t.link)
return t.link
return t
def _occurs(self, v, t):
t = self._find(t)
if t is v:
return True
if isinstance(t, _Fn):
return self._occurs(v, t.dom) or self._occurs(v, t.cod)
return False
def _unify(self, a, b):
a, b = self._find(a), self._find(b)
if a is b:
return
if isinstance(a, _TV):
if self._occurs(a, b):
raise UnificationError("infinite type")
a.link = b
elif isinstance(b, _TV):
self._unify(b, a)
else:
self._unify(a.dom, b.dom)
self._unify(a.cod, b.cod)
def _walk(self, e, env):
if isinstance(e, Var):
if e.name not in env:
raise UnboundVariableError(e.name)
return env[e.name]
if isinstance(e, Abs):
a = self._new()
return _Fn(a, self._walk(e.body, {**env, e.param: a}))
if isinstance(e, App):
tf = self._walk(e.fn, env)
ta = self._walk(e.arg, env)
r = self._new()
self._unify(tf, _Fn(ta, r))
return r
raise TypeError(f"unknown node: {e!r}")
def _show(self, t, names):
t = self._find(t)
if isinstance(t, _TV):
if t.uid not in names:
names[t.uid] = f"T{len(names)}"
return names[t.uid]
left = self._show(t.dom, names)
right = self._show(t.cod, names)
return f"({left} -> {right})"
Walkthrough: why \x. x x fails
xgets typeA.- In
x x, the function type isA, the argument type isA, and the result is a freshR. - We must unify
AwithA -> R.Aoccurs insideA -> R, so the occurs check raisesUnificationError.
For \f. \x. f x: f : A, x : B, result R, and unification sets A := B -> R. The overall type is (B -> R) -> (B -> R), which prints as ((T0 -> T1) -> (T0 -> T1)).
Complexity
Let n be the number of AST nodes.
- Tree walk:
O(n)steps, each creating at most one arrow, one variable, and one unification. - Unification: the find operation is near-constant amortized with path compression. The occurs check costs the size of the type it traverses, so the worst case is about
O(n^2). - Space:
O(n)for type nodes, plus recursion depth equal to the tree depth. - Caveat: internally types are shared graphs (DAGs), but the printed string expands shared parts and can be exponentially longer than the graph. Output size, not inference, is then the bottleneck.
Edge cases and common mistakes
- Forgetting the occurs check. Self-application would then silently produce a cyclic type and printing would loop forever.
- Mutating a shared environment. If the environment is modified in place, shadowing leaks out of the inner lambda. Copy on extend, or restore on exit.
- Naming variables at creation time. Output such as
T3 -> T3is wrong. Rename only when printing, in order of first appearance. - Not resetting the counter. Two calls on one object should not influence each other.
- Unbound names. Report them with a distinct error so they are not confused with type conflicts.
- Very deep trees. Recursion depth equals tree depth. Use an explicit stack or raise the recursion limit if inputs can be adversarial.
Follow-up: polymorphic let
Plain lambda parameters are monomorphic, so \id. (id id) style reuse at different types does not work. To support let x = e1 in e2 with generics, add type schemes (a type with universally quantified variables) to the environment. After inferring e1, generalize it by quantifying the variables that are not free in the current environment. At each use of x, instantiate the scheme with fresh variables. Tracking variable levels (depth of binding) makes generalization efficient without scanning the whole environment.