{
  "id": "hindley-milner-type-system",
  "title": "Hindley–Milner Type System",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Hindley–Milner type system supports automatic inference of principal types for programs with parametric, let-bound polymorphism.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "HM type system",
    "Damas–Milner type system",
    "Damas–Hindley–Milner type system"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/hindley-milner-type-system/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/hindley-milner-type-system/",
      "json": "https://aiwiki.page/zh/hindley-milner-type-system.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Hindley–Milner type system (HM) is a type system for programming languages that combines static typing, parametric polymorphism, and automatic type inference. In its standard form, it assigns types to a lambda calculus extended with let bindings, allowing many programs to be checked without explicit type annotations. Its defining property is the existence of principal types: whenever an expression is typable, it has a most general type from which all its other valid types can be obtained by substitution. HM forms an important theoretical foundation for type inference in functional programming languages, particularly the ML family."
    },
    {
      "heading": "Historical development",
      "text": "HM brings together several developments in the theory and implementation of programming languages.\n\nIn 1969, J. Roger Hindley established a principal-type result for combinatory logic, a formalism closely related to lambda calculus. Robin Milner developed a polymorphic typing discipline for ML and described an inference procedure, Algorithm W, in his 1978 paper A Theory of Type Polymorphism in Programming. Luis Damas and Milner subsequently established the principal-type-scheme result for the relevant functional language in their 1982 paper Principal Type-Schemes for Functional Programs.\n\nThese contributions explain the alternative names Damas–Milner and Damas–Hindley–Milner. The terminology is sometimes used broadly for related inference systems, but the core formal system is narrower than the complete type systems of modern ML-derived languages."
    },
    {
      "heading": "Core language and types",
      "text": "A minimal HM expression language contains variables, function abstraction, function application, and local definitions:\n\n\\[e ::= x \\mid \\lambda x.\\,e \\mid e_1\\,e_2 \\mid \\mathbf{let}\\ x=e_1\\ \\mathbf{in}\\ e_2.\\]\n\nConstants, tuples, lists, conditional expressions, and algebraic data constructors can be added with suitable typing rules.\n\nHM distinguishes monotypes from type schemes. A representative grammar is:\n\n\\[\\begin{aligned} \\tau &::= \\alpha \\mid b \\mid \\tau_1\\rightarrow\\tau_2 \\mid T(\\tau_1,\\ldots,\\tau_n),\\\\ \\sigma &::= \\forall\\alpha_1\\cdots\\alpha_n.\\,\\tau. \\end{aligned}\\]\n\nHere:\n\n- \\(\\alpha\\) is a type variable.\n- \\(b\\) is a base type, such as Int or Bool.\n- \\(\\tau_1\\rightarrow\\tau_2\\) is a function type.\n- \\(T\\) is a type constructor, such as List.\n- \\(\\sigma\\) is a type scheme whose listed variables are universally quantified.\n\nFunction arrows associate to the right, so \\(\\alpha\\rightarrow\\beta\\rightarrow\\alpha\\) means \\(\\alpha\\rightarrow(\\beta\\rightarrow\\alpha)\\).\n\nA type variable represents an unknown or arbitrary type, not a dynamically typed value. The scheme\n\n\\[\\forall\\alpha.\\,\\alpha\\rightarrow\\alpha\\]\n\ndescribes a function that can be instantiated at any type while preserving the relationship between its input and output types.\n\nQuantifiers occur only at the outermost level of a scheme, not inside function argument types. This restriction is central to HM’s tractable inference discipline."
    },
    {
      "heading": "Let-polymorphism",
      "text": "The characteristic feature of HM is let-polymorphism: a type inferred for a let-bound expression can be generalized, and separate uses of the bound name can instantiate that generalized type independently.\n\nFor example:\n\nlet id = fun x -> x in\n(id 3, id true)\n\nThe identity function receives the scheme\n\n\\[\\mathrm{id}:\\forall\\alpha.\\,\\alpha\\rightarrow\\alpha.\\]\n\nIts first use instantiates \\(\\alpha\\) as Int, and its second use instantiates it as Bool. The entire expression therefore has type\n\n\\[\\mathrm{Int}\\times\\mathrm{Bool}.\\]\n\nBy contrast, an ordinary lambda-bound parameter has one monotype within its scope. The expression\n\nfun f -> (f 3, f true)\n\nis not typable in basic HM when Int and Bool are distinct types: the two calls require incompatible argument types for the same monomorphic parameter.\n\nThis difference is intentional. HM does not provide unrestricted polymorphic function arguments.\n\nGeneralization and instantiation\n\nA typing environment \\(\\Gamma\\) maps program variables to type schemes. Let \\(\\operatorname{ftv}\\) denote the free type variables of a type or environment. Generalization is defined by\n\n\\[\\operatorname{Gen}(\\Gamma,\\tau) = \\forall\\bigl(\\operatorname{ftv}(\\tau) \\setminus\\operatorname{ftv}(\\Gamma)\\bigr).\\,\\tau.\\]\n\nOnly type variables not free in the surrounding environment may be generalized. Variables already constrained by the environment must retain those constraints.\n\nFor example:\n\nfun x ->\n  let f = fun y -> x in\n  ...\n\nIf x has type \\(\\alpha\\), then f can receive the scheme\n\n\\[\\forall\\beta.\\,\\beta\\rightarrow\\alpha,\\]\n\nbut not \\(\\forall\\alpha\\beta.\\,\\beta\\rightarrow\\alpha\\). Its result is the particular captured value x, whose type cannot change independently at each call.\n\nInstantiation replaces a scheme’s quantified variables with fresh type variables. Variables that are free rather than quantified remain shared with the environment."
    },
    {
      "heading": "Typing rules",
      "text": "The judgment\n\n\\[\\Gamma\\vdash e:\\tau\\]\n\nmeans that expression \\(e\\) has monotype \\(\\tau\\) under environment \\(\\Gamma\\).\n\nA compact presentation uses four central rules.\n\nVariable. A variable may be used at any monotype obtained by instantiating its scheme:\n\n\\[\\frac{ x:\\sigma\\in\\Gamma \\qquad \\tau\\text{ is an instance of }\\sigma }{ \\Gamma\\vdash x:\\tau }.\\]\n\nAbstraction. A function parameter is assigned a monotype while checking the body:\n\n\\[\\frac{ \\Gamma,x:\\tau_1\\vdash e:\\tau_2 }{ \\Gamma\\vdash\\lambda x.\\,e:\\tau_1\\rightarrow\\tau_2 }.\\]\n\nApplication. A function’s input type must agree with the argument’s type:\n\n\\[\\frac{ \\Gamma\\vdash e_1:\\tau_1\\rightarrow\\tau_2 \\qquad \\Gamma\\vdash e_2:\\tau_1 }{ \\Gamma\\vdash e_1\\,e_2:\\tau_2 }.\\]\n\nLet binding. The inferred type of the bound expression is generalized relative to the environment:\n\n\\[\\frac{ \\Gamma\\vdash e_1:\\tau_1 \\qquad \\Gamma,x:\\operatorname{Gen}(\\Gamma,\\tau_1)\\vdash e_2:\\tau_2 }{ \\Gamma\\vdash \\mathbf{let}\\ x=e_1\\ \\mathbf{in}\\ e_2:\\tau_2 }.\\]\n\nThese rules specify which expressions are well typed. An inference algorithm supplies an effective procedure for finding the types and substitutions needed to construct such derivations."
    },
    {
      "heading": "Type inference and Algorithm W",
      "text": "Algorithm W is the standard syntax-directed inference algorithm associated with HM. It traverses an expression and returns both a type and a substitution recording the constraints discovered during inference.\n\nThe central operation is unification: solving equations between type expressions. For example,\n\n\\[\\alpha\\rightarrow\\alpha = \\mathrm{Int}\\rightarrow\\beta\\]\n\nhas a most general solution\n\n\\[\\alpha=\\mathrm{Int}, \\qquad \\beta=\\mathrm{Int}.\\]\n\nA most general unifier makes only the identifications required by the equations; any other solution can be obtained by applying a further substitution.\n\nAlgorithm W handles the expression forms as follows:\n\n- Variable: look up its scheme and instantiate its quantified variables with fresh type variables.\n- Abstraction: give the parameter a fresh monotype, infer the body, and construct a function type.\n- Application: infer the function and argument, then unify the function’s type with an arrow from the argument type to a fresh result variable.\n- Let binding: infer the bound expression, apply the resulting substitution to the environment, generalize against that updated environment, and infer the body.\n\nUpdating the environment before generalization is essential: constraints discovered while checking the bound expression can restrict variables inherited from its context.\n\nThe occurs check\n\nUnification includes an occurs check, which prevents a type variable from being equated with a type expression containing itself. The equation\n\n\\[\\alpha=\\alpha\\rightarrow\\beta\\]\n\nhas no solution among finite HM types.\n\nConsequently, self-application,\n\nfun x -> x x\n\nis rejected. The parameter would have to be both an argument type and a function taking that same type as input.\n\nSimply dropping the occurs check does not yield ordinary HM. Supporting recursive types requires a different account of types and their equality."
    },
    {
      "heading": "Principal types and soundness",
      "text": "A principal type scheme captures every valid typing of an expression through instantiation, without unnecessarily fixing its type variables. For example,\n\nfun f -> fun x -> f x\n\nhas principal scheme\n\n\\[\\forall\\alpha\\beta.\\, (\\alpha\\rightarrow\\beta)\\rightarrow\\alpha\\rightarrow\\beta.\\]\n\nA type such as\n\n\\[(\\mathrm{Int}\\rightarrow\\mathrm{Bool}) \\rightarrow\\mathrm{Int}\\rightarrow\\mathrm{Bool}\\]\n\nis a valid instance, but is less general.\n\nFor the standard HM calculus, Algorithm W is sound and complete with respect to the typing rules: successful inference produces a valid typing, and a typable expression has a principal result recoverable by the algorithm. Principality is understood relative to the environment; constraints already present there remain in force.\n\nType safety is a related but distinct property. For a suitable operational semantics, well-typed programs do not encounter the kinds of type mismatch excluded by the typing rules—for example, applying a Boolean as though it were a function. This does not imply termination, the absence of all exceptions, or correctness with respect to an external specification. Such stronger properties belong to broader forms of formal verification."
    },
    {
      "heading": "Use in programming languages",
      "text": "HM is closely associated with ML and strongly influenced Standard ML, OCaml, and Haskell. These languages extend or modify the core system rather than implementing only the minimal calculus.\n\nCommon additions include:\n\n- Algebraic data types and pattern matching, which work naturally with polymorphic constructors.\n- Recursive definitions, usually checked using monomorphic assumptions within a recursive group before the completed bindings are generalized.\n- Modules and abstract types, which add separate mechanisms for organizing and hiding type information.\n- Qualified types, notably Haskell’s type-class constraints, which go beyond ordinary HM schemes.\n- Mutable state, which requires restrictions on generalization.\n\nIn compiler implementations, HM-style inference supports concise source programs while retaining static checks. Implementations often use mutable representations of type variables and efficient graph-based unification rather than directly reproducing Algorithm W’s substitution-based presentation."
    },
    {
      "heading": "Restrictions and extensions",
      "text": "Higher-rank polymorphism\n\nIn basic HM, a function parameter cannot itself be assigned an independently instantiable polymorphic scheme. A type such as\n\n\\[(\\forall\\alpha.\\,\\alpha\\rightarrow\\alpha) \\rightarrow (\\mathrm{Int}\\times\\mathrm{Bool})\\]\n\ncontains a quantifier inside a function argument and is outside the HM grammar.\n\nHigher-rank polymorphism supports such arguments. Languages offering it commonly require explicit annotations in places where ordinary HM would infer types automatically.\n\nSystem F provides a more expressive formal treatment of universal polymorphism, including explicit type abstraction and application. General reconstruction of omitted type information for unrestricted System F does not retain HM’s decidable inference problem.\n\nPolymorphic recursion\n\nUnder ordinary HM-style treatment of recursive definitions, a recursively defined name is monomorphic within its own definition. Polymorphic recursion, in which recursive calls use distinct type instances, is not inferred by standard Algorithm W.\n\nUnrestricted inference with polymorphic recursion is undecidable. Some languages permit particular polymorphically recursive definitions when an explicit type signature supplies the necessary information.\n\nMutable state and the value restriction\n\nUnrestricted generalization becomes unsound when combined naively with mutable references. A reference to an initially empty list must not be generalized so that one use can store integers while another reads the same contents as Booleans.\n\nML-family languages therefore restrict generalization. A common approach, the value restriction, broadly permits generalization for syntactic values while limiting it for expressions that may perform computation with effects. Exact rules vary by language; some use relaxed forms that recover additional safe generalization.\n\nFeatures outside the basic system\n\nSubtyping, overloaded operators, generalized algebraic data types, dependent types, and other advanced features require additional rules or different inference techniques. Some extensions preserve principal types under stated conditions; others introduce ambiguity, require annotations, or abandon global principal-type inference.\n\nAn implementation using HM-style unification therefore need not have all the metatheoretic properties of pure HM."
    },
    {
      "heading": "Complexity and practical limitations",
      "text": "HM inference is decidable, but decidability does not imply uniformly inexpensive inference. Despite good practical performance on many programs, inference for the general system has exponential worst-case behavior. Nested polymorphic definitions can generate very large types or force large implicit expansions during inference.\n\nEfficient representations can share repeated type structure and avoid needless copying, but they do not eliminate the underlying worst-case complexity. This distinction matters when assessing the computational complexity of an inference algorithm versus the size of a fully expanded inferred type.\n\nError reporting is another practical limitation. Unification may detect a contradiction far from the expression that introduced the programmer’s mistake. A compiler can therefore identify a valid type conflict while presenting an unhelpful location or explanation. Modern implementations supplement inference with source-location tracking, constraint provenance, annotations, and specialized diagnostics.\n\nFinally, a rejected program is not necessarily one that would fail during execution. Some expressions lie outside HM’s typing discipline because they need more expressive polymorphism, recursive types, or other extensions. HM deliberately balances expressiveness against automatic inference and strong, general typing guarantees."
    }
  ],
  "links": [
    "type-system",
    "functional-programming",
    "programming-language",
    "lambda-calculus",
    "formal-verification",
    "compiler",
    "computational-complexity"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}