TYPE INFERENCE
The compiler figures out what you meant
Inferring λx. x x gives x : α and one constraint, α = α → β. The unifier solves constraints by binding type variables, and it never checks whether α appears inside the type it binds α to. So it binds α ↦ α → β. What happens?
Hindley-Milner infers types with no annotations. It walks the program and gives every unknown a type variable. Each application f a adds a constraint τf = τa → β, tagged with its source location. Unification then solves the constraints into a substitution, or reports the first one that cannot hold.
Two details make it correct. The occurs check refuses to bind α to a type containing α. Let-generalisation turns a let-bound type into a scheme, ∀α. α → α, and every use gets fresh variables.
Constraint generation (one fresh variable per unknown):
n : int true, false : bool
x : instantiate(env[x])
λx. e : α → τe with x : α
f a : β and constraint τf = τa → β
let x = e1 in e2:
solve e1's constraints, τ1 = S(τe1)
x : ∀(ftv(τ1) − ftv(S env)). τ1 ← generalise
unify(a, b):
walk both through the substitution
same variable → ok
variable α vs τ → if α occurs in τ: FAIL (infinite type)
else bind α ↦ τ
int vs int → ok; int vs bool → FAIL
a1 → r1 vs a2 → r2 → unify(a1, a2); unify(r1, r2)
λx. x x: x : α, constraint α = α → β. α occurs in α → β: reject.
let id = λx. x in (id 1, id true): id : ∀α. α → α,
each use gets a fresh copy, so int and bool never meet. The strip checks that every type in the substitution is finite and that the final verdict matches a reference checker. NO OCCURS CHECK breaks the first at the bad unify and then the second too, since it reports an infinite type where the reference reports an error; MONOMORPHIC LET breaks only the second, by rejecting a correct program. Their FIX scenarios run the same programs with the switch back on.
This run types let id = λx. x in (id 1, id true) as int × bool. Pick a fault and a point so the checker gives the wrong answer for this program.
GOAL: the verdict differs from the reference checker
This unify has no occurs check, so α = α → β produces an infinite type. Add one: before binding a variable, walk the other type through subst and throw if the variable appears in it. Throw on every failure; return the substitution on success.
OCaml, Haskell, F#, Elm and the local inference in Rust and Swift all use unification; TypeScript uses a looser, subtyping-based inference. Error messages that point at the wrong line are usually a constraint solved in an unlucky order.
“How does type inference work?” or “implement unify.” Describe constraints and substitution, write unify with the occurs check, and explain why let is polymorphic but lambda parameters are not (the value restriction is the follow-up for languages with mutation).