Tuples, Lists & Pattern Matching

The compiler warns about non-exhaustive matches (warning 8) and unused cases (warning 11):

9.1 Tuples

let point = (3, 4)                   (* int * int *)
let person = ("Alice", 30, true)     (* string * int * bool *)
let (x, y) = point
fst point, snd point                 (* only for pairs *)
let swap (a, b) = (b, a)

9.1.1 Labeled tuples (OCaml 5.4+)

let p = (~x:1, ~y:2)                 (* x:int * y:int *)
let (~x, ~y) = p

9.2 Lists — immutable singly linked lists

[]                     (* empty: 'a list *)
[1; 2; 3]              (* note: semicolons! [1, 2, 3] is a list of ONE tuple *)
1 :: [2; 3]            (* cons: [1;2;3] *)
[1; 2] @ [3; 4]        (* append: O(length of first) *)
List.hd [1;2], List.tl [1;2]   (* avoid: raise on [] — use pattern matching *)

9.3 Pattern matching on lists

let rec length = function
  | [] -> 0
  | _ :: tl -> 1 + length tl

let rec sum = function
  | [] -> 0
  | x :: xs -> x + sum xs

let describe = function
  | [] -> "empty"
  | [x] -> "one: " ^ string_of_int x
  | [x; y] -> Printf.sprintf "two: %d %d" x y
  | x :: _ :: _ -> "many, starting with " ^ string_of_int x

9.4 Kinds of patterns

0, 'a', "hi", true [], [a; b], h:: t Some x, Node (l, v, r) { name; age = 30; _ } 'a' | 'e' | 'i' (x:: _) as whole x when x > 0 exception Not_found (in match)

9.5 Exhaustiveness & redundancy

The compiler warns about non-exhaustive matches (warning 8) and unused cases (warning 11):

Treat these warnings as errors — they are one of OCaml's best features.

let f = function
  | Some x -> x
(* Warning 8: this pattern-matching is not exhaustive.
   Here is an example of a case that is not matched: None *)

9.6 Nested patterns & as

let rec dedup = function
  | x :: (y :: _ as rest) when x = y -> dedup rest
  | x :: rest -> x :: dedup rest
  | [] -> []

9.7 Destructuring in let and fun

let (a, b) = (1, 2)
let add_pair (x, y) = x + y
let first_of_three (x, _, _) = x
List.map (fun (k, v) -> k ^ "=" ^ v) [("a","1"); ("b","2")]