25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ere is nothing more practical than a good theory.<br />

— James C. Maxwell<br />

Hindley-Milner Inference<br />

e Hindley-Milner type system ( also referred to as Damas-Hindley-Milner or HM ) is a family of<br />

type systems that admit the serendipitous property of having a tractable algorithm for determining types<br />

from untyped syntax. is is achieved by a process known as unification, whereby the types for a wellstructured<br />

program give rise to a set of constraints that when solved always have a unique principal type.<br />

e simplest Hindley Milner type system is defined by a very short set of rules. e first four rules<br />

describe the judgements by which we can map each syntactic construct (Lam, App, Var, Let) to their<br />

expected types. We’ll elaborate on these rules shortly.<br />

x : σ ∈ Γ<br />

Γ ⊢ x : σ<br />

Γ ⊢ e 1 : τ 1 → τ 2 Γ ⊢ e 2 : τ 1<br />

Γ ⊢ e 1 e 2 : τ 2<br />

Γ, x : τ 1 ⊢ e : τ 2<br />

Γ ⊢ λ x . e : τ 1 → τ 2<br />

Γ ⊢ e 1 : σ Γ, x : σ ⊢ e 2 : τ<br />

Γ ⊢ let x = e 1 in e 2 : τ<br />

Γ ⊢ e : σ α /∈ ftv(Γ)<br />

Γ ⊢ e : ∀ α . σ<br />

Γ ⊢ e : σ 1 σ 1 ⊑ σ 2<br />

Γ ⊢ e : σ 2<br />

(T-Var)<br />

(T-App)<br />

(T-Lam)<br />

(T-Let)<br />

(T-Gen)<br />

(T-Inst)<br />

Milner’s observation was that since the typing rules map uniquely onto syntax, we can in effect run the<br />

typing rules “backwards” and whenever we don’t have a known type for an subexpression, we “guess” by<br />

putting a fresh variable in its place, collecting constraints about its usage induced by subsequent typing<br />

judgements. is is the essence of type inference in the ML family of languages, that by the generation<br />

and solving of a class of unification problems we can reconstruct the types uniquely from the syntax.<br />

e algorithm itself is largely just the structured use of a unification solver.<br />

79

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!