Advanced Topic 44 of 50 Languages & Compilers
Hindley-Milner Inference
Classic algorithm for polymorphic type inference.
How it works
Hindley-Milner is a type inference algorithm for the polymorphic lambda calculus that infers the most general, principal type of an expression without annotations. It assigns fresh type variables, generates equality constraints from the structure of the code and solves them by unification. Let-polymorphism generalizes the types of let-bound definitions so functions like identity can be used at several types. Algorithm W and algorithm J are standard formulations.
Step-by-step walkthrough
- Assign unknown type variables to each expression.
- Collect constraints from how values are used, such as x + 1 means x is a number.
- Unification solves the constraints.
- The most general type comes out, like a to a for identity.
- ML, Haskell and OCaml use it.
Where it is used
It is the core of type inference in ML, OCaml, Haskell and F#, and influenced Rust, Elm and TypeScript's inference.
Common pitfall
It does not support all features directly: higher-rank types, subtyping, overloading and type classes need extensions or annotations. Error messages can point far from the real mistake because unification fails where constraints meet. The monomorphism restriction and value restriction limit polymorphism to preserve soundness with mutation. Add annotations to guide errors and document intent.
Where it fits in the course
Hindley-Milner Inference is topic 44 of 50 in Languages & Compilers, rated Advanced. It follows Ownership and Borrowing. The next topic is Dependent Types.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Hindley-Milner Inference?
Where do people use Hindley-Milner Inference?
What is the most common mistake with Hindley-Milner Inference?
What should I learn before this topic?
How can I practice it?
Is Hindley-Milner Inference hard to learn?
How long does it take to learn Hindley-Milner Inference?
Which topics are related to Hindley-Milner Inference?
What should I study after Hindley-Milner Inference?
Related topics
- Ownership and Borrowing (Languages & Compilers)
- Dependent Types (Languages & Compilers)
- Pattern Matching (Languages & Compilers)
- Linear and Affine Types (Languages & Compilers)
- Bayesian Inference (Math for Computing)