Type inference in Haskell


Type inference vs type-checking

Standard type checking
int f(int x) { return x * x }
int g(int x) { return x * f(x) }
  • Examine body of each function 
  • Use declared types to check agreement

Type inference
int f(int x) { return x * x }
int g(int x) { return x * f(x) }
  • Examine code without type information 
  • Infer the most general types that could have been declared

Haskell examples


Type inference algorithm

  1. Assign a type or type variable to the expression and each subexpression. 
  1. Generate a set of constraints on types, using the parse tree of the expression. 
  1. Solve these constraints by unification.

Example 1

1. Assign a type variable to the expression and each subexpression

2. Generate a set of constraints on types, using the parse tree of the expression


3. Solve the generated constraints using unification

Step 1
Step 2
Step 3

Example 2: Polymorphic functions

1. Assign a type variable to the expression and each subexpression

2. Generate a set of constraints on types, using the parse tree of the expression

3. Solve the generated constraints using unification

Step 1
Step 2