Algorithm W (source code)

= Algorithm W
{c}

<Algorithm W> infers <data types> for a pure <lambda calculus> with <let polymorphism>. Write $W(\Gamma,e)=(S,\tau)$, where $S$ is a <type substitution> and $\tau$ the inferred <data type>. Composition $S_2S_1$ means applying $S_1$ first. The following presentation uses <type schemes> explicitly.<A Theory of Type Polymorphism in Programming by Robin Milner>[sections 4.1–4.2, Algorithm W and its soundness]{ref}

For a <program identifier>, take a fresh instance of its <type scheme> in the <typing context>. For $\lambda x.e$, introduce fresh $\alpha$, infer $(S,\tau)=W(\Gamma[x:\alpha],e)$, and return $(S,S\alpha\to\tau)$.

For an application $e_1e_2$, compute $(S_1,\tau_1)=W(\Gamma,e_1)$ and $(S_2,\tau_2)=W(S_1\Gamma,e_2)$. With fresh $\beta$, let $U$ be the <most general unifier> of $S_2\tau_1$ and $\tau_2\to\beta$. Return $(US_2S_1,U\beta)$. An incompatible base <data type> or failed <occurs check> rejects the expression.

For `let x = e1 in e2`, first infer $(S_1,\tau_1)$. Generalize exactly those <type variables> of $\tau_1$ not free in $S_1\Gamma$, producing a <type scheme> $\sigma$. Infer $(S_2,\tau_2)$ for $e_2$ under $S_1\Gamma[x:\sigma]$ and return $(S_2S_1,\tau_2)$.

For example, `let id = \x -> x in let a = id 3 in id True` has a <Boolean data type> result. The <identity function> receives <type scheme> $\forall\alpha.\alpha\to\alpha$, then separate uses instantiate it at <integer> and <Boolean data types>. A parameter to a <lambda abstraction> instead has one shared <monomorphic type>; treating that parameter like a let-bound <type scheme> would accept programs outside this <type system>.