Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 40 ยท Language Basics

Type Inference and Polymorphism in OCaml

See how OCaml infers types without annotations, read type signatures, use 'a type variables for polymorphism, add annotations when useful and decode common type errors.

One of OCaml's best features is that you almost never write types, yet every expression is checked. The compiler uses a type inference algorithm (Hindley-Milner, with extensions) to work out the most general type of each definition. This lesson shows how to read those inferred types, how polymorphism arises, when to add annotations, and how to decode the most common type errors.

Reading an inferred type

Each toplevel answer shows the inferred type:

OCAML
# let double x = x * 2;;
val double : int -> int = <fun>

# let greet name = "Hi " ^ name;;
val greet : string -> string = <fun>

# let add a b = a + b;;
val add : int -> int -> int = <fun>

Read int -> int -> int as "takes an int, then another int, returns an int". (Why it is written that way is the subject of currying.)

How did the compiler know? Each operator or function you use has a known type: * is int -> int -> int, so x must be int. The compiler gathers such facts and solves them like equations. If they contradict, you get a type error.

Polymorphism: 'a

Sometimes the compiler cannot (and does not need to) pin a type down:

OCAML
# let identity x = x;;
val identity : 'a -> 'a = <fun>

# let first (a, _) = a;;
val first : 'a * 'b -> 'a = <fun>

# let pair_up x y = (x, y);;
val pair_up : 'a -> 'b -> 'a * 'b = <fun>

'a and 'b are type variables, pronounced "alpha" and "beta". A function with type variables is polymorphic: it works for any type. identity 3 is int, identity "x" is string. The same type variable in several places expresses a link: 'a -> 'a means "result type equals argument type".

Check yourself on first: the pair may hold two different types ('a * 'b), and the result has the type of the first part.

The standard library is full of polymorphic functions:

OCAML
# List.length;;
- : 'a list -> int = <fun>
# List.rev;;
- : 'a list -> 'a list = <fun>
# fst;;
- : 'a * 'b -> 'a = <fun>

Weak type variables

You may occasionally see '_weak1:

OCAML
# let cell = ref None;;
val cell : '_weak1 option ref = {contents = None}

A '_weak variable means "this is a single unknown type, which will be fixed the first time you use it". It appears for mutable values, because a polymorphic mutable cell would be unsafe. Once you store an int, the type becomes int option ref permanently.

Annotations

You are free to write types explicitly:

OCAML
let add (a : int) (b : int) : int = a + b

The pattern is (name : type) for parameters and : type before = for the result. Annotations never change meaning; the compiler checks they agree with its inference. Use them for:

  1. Documentation at module boundaries (usually in .mli files instead).
  2. Better error messages in a complicated function: with an annotation, the error appears at the line where your intention and reality part.
  3. Restricting a polymorphic function: let to_float (x : int) = float_of_int x.

You can also annotate an expression: (5 : int).

Type errors: how to read them

OCAML
let average a b = (a + b) / 2.0
TEXT
Error: The constant 2.0 has type float but an expression was expected of type int

Message wording changes between versions, but the structure is stable: the compiler points at an expression, says what type it has and what type was expected from context. Here / is integer division, so 2.0 is out of place. The fix: use the float operators and convert: (float_of_int a +. float_of_int b) /. 2.0.

Another classic: forgetting an else branch or returning different types from branches, as seen in Conditionals.

A third: applying a function to too many arguments:

OCAML
let f x = x + 1
let bad = f 1 2   (* error: f takes one argument, it is applied to too many *)

When an error baffles you, ask the toplevel for the type of subexpressions: type f;; alone, or hover in your editor, where the language server shows each type.

Value restriction and generalization (a peek)

Only function definitions are generalized to polymorphic types. let x = ref [] stays weakly polymorphic, as seen above, and so does let f = List.map (fun x -> x). If you meet '_weak where you wanted 'a, turn the definition into a function with an explicit parameter (eta-expansion): let f l = List.map (fun x -> x) l.

Types are erased at run time

OCaml does not keep types at run time, which is why generic code is fast and there is no typeof. The compiler's checks are the only checks, so you can trust them: a well-typed OCaml program does not crash with a "type error" while running (it may still raise exceptions such as Not_found).

A stand-in: a tiny type inferencer

This JavaScript stand-in infers types of simple expressions from a toy syntax tree. It shows the idea: operators carry known types, and conflicts are errors.

JS Stand-in: infer or reject

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the type 'a -> 'a describe?

    The repeated variable 'a ties the result type to the argument type; the function is polymorphic.
  2. 2. What is the type of let first (a, _) = a?

    The pair may contain two different types; the result has the first component's type.
  3. 3. What is a good reason to add a type annotation?

    Annotations are optional checks and documentation. They have no run-time effect.
  4. 4. What does '_weak1 mean?

    Weak type variables appear for mutable or non-function values and become concrete after first use.

Summary

  • OCaml infers the most general type of each expression; annotations are optional.
  • 'a, 'b are type variables; functions using them are polymorphic.
  • Weak variables ('_weak1) arise for mutable values and get fixed at first use.
  • Type errors say what type was found and what was expected; check operators first.
  • Types are erased at run time, so checked code is also fast.

Next: Defining functions