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.
# 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".
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
let apply_twice f x = f (f x)the compiler reasons:
fis applied tox, sofis a function:f : 'a -> 'bwithx : 'a.fis applied again to the resultf x : 'b, so'bmust equal'a.- 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:
# 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:
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:
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:
# 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:
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)?
'a -> 'a -> 'a * 'a'a -> 'b -> 'a * 'bint -> int -> int * int'a * 'b
How do you write the type of a list of trees of strings, given type 'a tree = ...?
tree string liststring tree listlist (tree string)'string tree list
What does a '_weak1 type variable mean?
- The function is polymorphic forever
- A single unknown type, fixed by the first use
- A type error
- The value is mutable