typestar

Tuples in OCaml

Pair values without ceremony; patterns take them apart.

(* Tuples pair values without ceremony; patterns take them apart. *)
let site = (52.74, 0.39)
let lat, lon = site

(* Functions return tuples for free multiple results. *)
let measure () = (14.5, 31)

let () =
  Printf.printf "Shore at %.2f N, %.2f E\n" lat lon;
  let temp, animals = measure () in
  Printf.printf "%.1f C with %d animals\n" temp animals;
  (* fst, snd, and _ cover the quick accesses. *)
  Printf.printf "Latitude alone: %.2f\n" (fst site);
  let _, count_only = measure () in
  Printf.printf "Count alone: %d\n" count_only

How it works

  1. let lat, lon = site destructures in one line.
  2. Functions return tuples for free multiple results.
  3. fst, snd, and _ cover the quick accesses.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
527
Tokens
97
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 2 of 3 in Types, step 16 of 29 in Language basics.

← Previous Next →

Tuples in other languages