Every time you write map f xs in Haskell or List.map f xs in OCaml and the compiler accepts it without a single type annotation, you are watching Hindley-Milner type inference at work. The compiler deduces that f must be a function, that xs must be a list whose elements match f's input, and that the result is a list of whatever f produces — all from the expression alone, with no help from you.
The algorithm was discovered independently by J. Roger Hindley (1969) and Robin Milner (1978), and later refined by Luis Damas (1982) into the form used today, often called Damas-Milner or Algorithm W. It is one of the most influential results in programming-language theory: a solved problem with a clean, complete answer.
The core idea is unification: when the algorithm sees f x, it generates the constraint that the type of f must be of the form for some type variables and , that the type of x must unify with , and that the whole expression has type . Solving all such constraints simultaneously yields the principal type — the most general type that the expression can have. Any other valid type is just a specialization of it.
What makes this remarkable is the guarantee: if a principal type exists, Algorithm W finds it in nearly linear time. If no type exists, the algorithm reports a type error. There is no ambiguity and no need to guess.
Comments
Loading comments...