TExcelTAD
Home › OCaml › OCaml Tuples

OCaml Tuples

A tuple groups a fixed number of values, possibly of different types, into one value. Tuples are written with commas, usually inside parentheses:

ocaml · try it yourself
let point = (3, 4)
let person = ("Marie", 1867, true)

let () =
  let x, y = point in
  let name, born, physicist = person in
  Printf.printf "x=%d y=%d\n" x y;
  Printf.printf "%s, born %d, physicist: %b\n" name born physicist
x=3 y=4
Marie, born 1867, physicist: true

The types are written with *: point : int * int and person : string * int * bool. The * is a reminder of the mathematical "product" of sets.

Lists versus tuples

List Tuple
Length any, changes from list to list fixed by the type
Element types all the same can differ
Syntax [1; 2; 3] (1, "two", 3.0)
Type int list int * string * float
Access pattern matching, List functions pattern matching

Accessing elements

The usual way to read a tuple is to destructure it with a pattern, as above. For pairs only, fst and snd return the first and second element:

ocaml · try it yourself
let () =
  let pair = ("key", 99) in
  print_endline (fst pair);
  print_int (snd pair);
  print_newline ()
key
99

There is no third function: for bigger tuples, use a pattern like let (_, _, c) = triple in ..., or switch to a record.

Returning several values

Tuples are the simplest way for a function to return more than one result:

ocaml · try it yourself
let divide_with_remainder a b = (a / b, a mod b)

let stats lst =
  let n = List.length lst in
  let total = List.fold_left ( + ) 0 lst in
  let lowest = List.fold_left min max_int lst in
  let highest = List.fold_left max min_int lst in
  (n, total, lowest, highest)

let () =
  let q, r = divide_with_remainder 47 6 in
  Printf.printf "47 = 6 * %d + %d\n" q r;
  let n, total, lo, hi = stats [ 14; 3; 27; 8 ] in
  Printf.printf "n=%d total=%d min=%d max=%d\n" n total lo hi
47 = 6 * 7 + 5
n=4 total=52 min=3 max=27

Tuples in patterns and lists

Tuples combine well with pattern matching and with lists of pairs:

ocaml · try it yourself
let describe_point (x, y) =
  match (x, y) with
  | 0, 0 -> "origin"
  | 0, _ -> "on the y axis"
  | _, 0 -> "on the x axis"
  | _ when x = y -> "on the diagonal"
  | _ -> "somewhere else"

let () =
  [ (0, 0); (0, 5); (2, 0); (3, 3); (1, 4) ]
  |> List.iter (fun (x, y) -> Printf.printf "(%d, %d): %s\n" x y (describe_point (x, y)))
(0, 0): origin
(0, 5): on the y axis
(2, 0): on the x axis
(3, 3): on the diagonal
(1, 4): somewhere else

Note that a function can take a tuple pattern directly as its parameter: let describe_point (x, y) = ....

Comparing tuples

=, < and compare work on tuples element by element from left to right. This makes tuples handy as sort keys:

ocaml · try it yourself
let () =
  let results = [ ("Lee", 82); ("Ana", 95); ("Bo", 82); ("Cy", 70) ] in
  (* sort by score descending, then by name ascending *)
  let sorted = List.sort (fun (n1, s1) (n2, s2) -> compare (s2, n1) (s1, n2)) results in
  List.iter (fun (name, score) -> Printf.printf "%-4s %d\n" name score) sorted;
  Printf.printf "%b\n" ((1, "b") < (2, "a"))
Ana  95
Bo   82
Lee  82
Cy   70
true

Tip: When a tuple has more than three fields, or its fields have the same type and could be confused ((int * int * int) for a date?), use a record with named fields instead. That is the next lesson.

Test yourself

What is the type of ("x", 1.5, 'c')?

  1. string list
  2. string * float * char
  3. (string, float, char)
  4. tuple

What does snd (10, "ten") return?

  1. 10
  2. "ten"
  3. (10, "ten")
  4. An error

Is (1, "z") < (2, "a") true or false?

  1. true
  2. false
  3. A type error
  4. It depends on the platform