Infer the type of map function using Hindley-Milner. Walk through unification steps to derive (a -> b) -> [a] -> [b].
Assistant
Explaining Hindley-Milner inference for map
I'll step through assigning fresh type variables to map's parameters and body, generating constraints from pattern matching and function applications, then unify these constraints to derive the principal type ∀a b. (a -> b) -> [a] -> [b].
A standard way to present the inference is to start from a definition such as
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
map f xs =
case xs of
[] -> []
(x:xs) -> f x : map f xs
Algorithm W works by walking the syntax tree, assigning fresh type variables and generating equations between them, and then unifying those equations.
One possible derivation looks like this:
Give map a provisional type t₀ → t₁ → t₂, and introduce fresh variables for its arguments: f : t₀, xs : t₁.
Analyse the case on xs. Both branches must have the same result type; introduce a fresh variable α to stand for the element type of xs and a fresh variable β for the result of applying f. Pattern‑matching on [] forces t₁ to be a list type, so you get the equation
[
t₁ = [\alpha].
]
The expression [] in the first branch has type [γ] for some fresh γ.
In the (x:xs) branch, the pattern forces x : α and xs' : [\alpha]. The expression f x : map f xs' is built with (:), which has type ∀δ.(δ → [δ] → [δ]), so for some δ you must have
[
f,x : \delta,\qquad map,f,xs' : [\delta].
]
The application f x forces f to have a function type α → β, and yields the equation
[
t₀ = \alpha \to \beta,\qquad \delta = \beta.
]
The recursive call map f xs' applies map to two arguments, so if map has type t₀ → t₁ → t₂ then
[
map,f : t₁ \to t₂,\qquad map,f,xs' : t₂.
]
For this to be consistent with the cons above, you need t₂ = [\beta].
Finally, the two branches of the case must have the same type, so the [γ] from the [] branch must unify with the [β] from the cons branch, giving γ = β.
Collecting the constraints you have
t₁ = [α]
t₀ = α → β
t₂ = [β]
Substituting these back into the provisional type t₀ → t₁ → t₂ yields
[
(\alpha \to \beta) \to [\alpha] \to [\beta].
]
Since α and β were arbitrary fresh variables, they are both universally quantified. The principal type scheme inferred for map is therefore