Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 40 ยท Language Basics

Tuples and Unit in OCaml

Group values of different types with OCaml tuples, take them apart with patterns, use fst and snd, return several results from a function, and understand the unit type.

A tuple groups a fixed number of values, which may have different types, into one value. You do not declare tuples; you just write them with commas. Tuples are one of the most-used features in everyday OCaml, together with the special unit value you have already seen in let () = ....

Creating tuples

OCAML
# (1, "one");;
- : int * string = (1, "one")
# ("Ada", 36, true);;
- : string * int * bool = ("Ada", 36, true)

The type of a tuple uses * between the component types. int * string is a pair of an int and a string. The parentheses are optional in many places, but they make code clearer, so most programmers write them.

Tuples are immutable and have a fixed size. The type int * int and the type int * int * int are different types, so you cannot accidentally pass a triple where a pair is expected.

Taking tuples apart

The simplest way is a pattern on the left of let:

OCAML
let (name, age) = ("Grace", 85)
(* name = "Grace", age = 85 *)

For pairs only, there are two functions in the standard library:

OCAML
# fst (3, "x");;
- : int = 3
# snd (3, "x");;
- : string = "x"

There are no built-in functions for triples and bigger tuples, because patterns do the job better:

OCAML
let (x, y, _) = (1, 2, 3)      (* ignore the third *)

Tuples in function arguments and results

A function can take a tuple parameter by writing the pattern in the parameter list:

OCAML
let distance (x1, y1) (x2, y2) =
  sqrt ((x2 -. x1) ** 2. +. (y2 -. y1) ** 2.)

Its type is float * float -> float * float -> float. This is usually better than a function with four separate arguments when the numbers belong together as points.

Tuples are also the standard way to return several values:

OCAML
let min_max a b = if a < b then (a, b) else (b, a)

let (low, high) = min_max 9 4
(* low = 4, high = 9 *)

Another typical use is List.partition, which returns two lists:

OCAML
# List.partition (fun n -> n > 2) [1; 2; 3; 4];;
- : int list * int list = ([3; 4], [1; 2])

Tuples compare structurally

OCAML
# (1, "a") = (1, "a");;
- : bool = true
# (1, "a") < (1, "b");;
- : bool = true

Comparison goes component by component, left to right (lexicographic order), so tuples work as keys when sorting:

OCAML
let people = [("Zoe", 25); ("Adam", 40); ("Adam", 30)]
let sorted = List.sort compare people
(* [("Adam", 30); ("Adam", 40); ("Zoe", 25)] *)

Tuples or records?

A tuple is quick, but its parts have no names, so (3, 4) could be a point, a version number or a time. Once a structure has more than two or three parts, or is used in many places, define a record instead; records are in Records.

The unit type

unit is the type with exactly one value, written (). You can think of it as the empty tuple. It carries no information, so it appears where a value is required but nothing meaningful exists:

  • Functions run for their side effects return unit: print_string : string -> unit.
  • A function with no useful argument takes (): let hello () = print_endline "hi".
  • if without else must have type unit in its branch.
OCAML
let hello () = print_endline "hi"

let () =
  hello ();
  hello ()

Why take () at all? Because let hello = print_endline "hi" would print once, immediately, while defining hello. A function that takes () delays the effect until you call it.

The ; operator expects the left side to be unit. If it is not, the compiler warns you that a result is being ignored, which often points to a bug:

OCAML
let () =
  List.map (fun x -> x + 1) [1; 2; 3];   (* warning: this expression should have type unit *)
  print_endline "done"

If you really want to throw a value away, use ignore (...) or let _ = ... in.

A stand-in: pairs and destructuring

JavaScript arrays can imitate tuples. This stand-in defines minMax, destructures the result and sorts pairs lexicographically like OCaml's compare.

JS Stand-in: tuples as fixed-size arrays

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 is the type of (1, "a", true)?

    A tuple's type lists the component types separated by *.
  2. 2. What does fst (7, 8) return?

    fst returns the first component of a pair; snd the second.
  3. 3. Why does let hello () = print_endline "hi" take ()?

    Without the unit parameter the expression would run once when defining the name.
  4. 4. Which is true of tuples?

    Tuples are immutable with fixed size, and each position can have a different type.

Summary

  • A tuple groups a fixed number of values of possibly different types: (1, "a") has type int * string.
  • Destructure with patterns; fst and snd work for pairs only.
  • Tuples are the usual way to return multiple results.
  • unit has the single value (); it marks side-effecting functions and delays effects.
  • Use records when parts need names.

Next: Conditionals and comparison