OCaml Easy · Lesson 1 · On the house

Polymorphism and type variables

'a in signatures, generic functions, and how inference generalizes. Lesson 1 is free — on the house.

Lessons · OCaml Easy · Lesson 1 of 10 · On the house

Polymorphism and type variables

'a in signatures, generic functions, and how inference generalizes.

Illustration for OCaml
Lesson 1 is on the house.

let id x = x has type 'a -> 'a: 'a (read "alpha") is a type variable standing for any type. The same function works on ints, strings and lists.

List.length : 'a list -> int works for any element type, and List.map : ('a -> 'b) -> 'a list -> 'b list can change the element type.

Inference generalizes top-level let definitions automatically. You never declare generics.

Some values cannot be generalized: let r = ref [] gets a weak type '_weak1 list ref, fixed by its first use. This prevents putting an int and a string into the same ref.

Read signatures in utop with #show List.map;;, or hover in an editor using Merlin or ocaml-lsp.

'a functions

let id x = x
let pair x y = (x, y)
let swap (a, b) = (b, a)

let () =
  print_endline (id "same");
  print_endline (string_of_int (id 42));
  let (s, n) = swap (pair 1 "one") in
  print_endline (s ^ string_of_int n);
  print_endline (string_of_int (List.length ["a"; "b"]))
Match this when you type.

Quiz

What is the type of let id x = x?

Quiz

What does 'a mean in a signature?

Quiz

What type does List.map have?

Quiz

Why does ref [] get a weak type?

Check

Match the still for: Polymorphism and type variables.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.