TExcelTAD
Home › OCaml › OCaml Polymorphism and Type Inference

OCaml Polymorphism and Type Inference

Some functions do not care about the type of their data. Reversing a list works the same for a list of ints and a list of strings. OCaml expresses this with type variables such as 'a (read "alpha") and 'b ("beta"). A function whose type contains type variables is polymorphic: it works for every type.

ocaml
# let identity x = x;;
val identity : 'a -> 'a = <fun>
# List.rev;;
- : 'a list -> 'a list = <fun>
# fst;;
- : 'a * 'b -> 'a = <fun>

'a -> 'a says "give me a value of any type, and I return a value of the same type".

ocaml · try it yourself
let identity x = x
let swap (a, b) = (b, a)
let first_or default = function [] -> default | x :: _ -> x

let () =
  Printf.printf "%d %s\n" (identity 7) (identity "seven");
  let n, s = swap ("left", 1) in
  Printf.printf "%d %s\n" n s;
  Printf.printf "%d\n" (first_or 0 [ 4; 5 ]);
  Printf.printf "%s\n" (first_or "none" [])
7 seven
1 left
4
none

The same first_or is used once with ints and once with strings. The compiler generates only one version of the function; polymorphism has no runtime cost.

How inference works

OCaml's type inference (the Hindley–Milner algorithm) works like solving equations. For

ocaml
let apply_twice f x = f (f x)

the compiler reasons:

  1. f is applied to x, so f is a function: f : 'a -> 'b with x : 'a.
  2. f is applied again to the result f x : 'b, so 'b must equal 'a.
  3. The result is f (f x) : 'a.

So apply_twice : ('a -> 'a) -> 'a -> 'a. Whenever the code forces a concrete type, such as using + (ints only), the variable is replaced:

ocaml
# let add_pair (a, b) = a + b;;
val add_pair : int * int -> int = <fun>
# let pair_with x y = (x, y);;
val pair_with : 'a -> 'b -> 'a * 'b = <fun>

Polymorphic data types

Type definitions can take type parameters too. The parameter goes before the type name:

ocaml · try it yourself
type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree

let rec insert x = function
  | Leaf -> Node (Leaf, x, Leaf)
  | Node (l, v, r) as node ->
      if x < v then Node (insert x l, v, r)
      else if x > v then Node (l, v, insert x r)
      else node

let rec to_list = function
  | Leaf -> []
  | Node (l, v, r) -> to_list l @ [ v ] @ to_list r

let () =
  let numbers = List.fold_left (fun t x -> insert x t) Leaf [ 5; 2; 8; 1; 9; 2 ] in
  let words = List.fold_left (fun t x -> insert x t) Leaf [ "pear"; "apple"; "fig" ] in
  print_endline (String.concat " " (List.map string_of_int (to_list numbers)));
  print_endline (String.concat " " (to_list words))
1 2 5 8 9
apple fig pear

insert uses < and >, which work on any type, so the tree is polymorphic: int tree and string tree both work. option, list and result are defined the same way in the standard library.

Type annotations

Annotations can document or restrict a type. 'a in an annotation is a name for a type the compiler may choose, which can surprise beginners:

ocaml · try it yourself
let wrap (x : 'a) : 'a list = [ x ]
let restricted (x : int) : int list = [ x ]
let explicitly_poly : 'a. 'a -> 'a list = fun x -> [ x ]

let () =
  Printf.printf "%d %d %d\n"
    (List.length (wrap "a"))
    (List.length (restricted 3))
    (List.length (explicitly_poly 2.5))
1 1 1

'a. 'a -> 'a list (an explicit universal annotation) demands that the function really is polymorphic, and the compiler rejects it otherwise.

The value restriction

A partially applied function may get a weak type variable, written '_weak1. It is not yet decided, and is fixed by the first use:

ocaml
# let ids = List.map (fun x -> x);;
val ids : '_weak1 list -> '_weak1 list = <fun>
# ids [1; 2];;
- : int list = [1; 2]
# ids;;
- : int list -> int list = <fun>

This rule keeps mutable data (like references) type-safe. The fix, if you need a truly polymorphic function, is to add the argument back (eta-expansion): let ids l = List.map (fun x -> x) l.

Generic comparison

=, < and compare are polymorphic: 'a -> 'a -> bool. They compare structure, which is convenient, but they raise an exception on function values and may not match the order you want for your own types:

ocaml · try it yourself
let () =
  Printf.printf "%b\n" ([ Some 1; None ] = [ Some 1; None ]);
  Printf.printf "%d\n" (compare (Some 3) None);
  (try ignore ((fun x -> x) = (fun x -> x)) with Invalid_argument msg -> print_endline msg)
true
1
compare: functional value

Test yourself

What is the type of let pair x y = (x, y)?

  1. 'a -> 'a -> 'a * 'a
  2. 'a -> 'b -> 'a * 'b
  3. int -> int -> int * int
  4. 'a * 'b

How do you write the type of a list of trees of strings, given type 'a tree = ...?

  1. tree string list
  2. string tree list
  3. list (tree string)
  4. 'string tree list

What does a '_weak1 type variable mean?

  1. The function is polymorphic forever
  2. A single unknown type, fixed by the first use
  3. A type error
  4. The value is mutable