TExcelTAD
Home › OCaml › OCaml Records

OCaml Records

A record is like a tuple whose fields have names. You declare a record type once, listing each field and its type, and then create values with { field = value; ... }.

ocaml · try it yourself
type book = {
  title : string;
  author : string;
  year : int;
  pages : int;
}

let () =
  let b = { title = "The Hobbit"; author = "J. R. R. Tolkien"; year = 1937; pages = 310 } in
  Printf.printf "%s by %s (%d), %d pages\n" b.title b.author b.year b.pages
The Hobbit by J. R. R. Tolkien (1937), 310 pages

Fields are read with dot notation: b.title. The order of fields in a record expression does not matter, but every field must be given.

Type inference with records

You never have to say which record type a value has. OCaml looks at the field names to find the type:

ocaml
# let age b = 2026 - b.year;;
val age : book -> int = <fun>

If two record types in the same scope share a field name, the most recently defined one wins, and you may need an annotation such as (b : book). Giving fields distinct names avoids the problem.

Functional update

Records are immutable by default. To "change" a field, build a new record with { r with field = new_value }. The fields you don't mention are copied:

ocaml · try it yourself
type account = { owner : string; balance : int; frozen : bool }

let deposit acc amount = { acc with balance = acc.balance + amount }
let freeze acc = { acc with frozen = true }

let show acc =
  Printf.printf "%s: %d%s\n" acc.owner acc.balance (if acc.frozen then " (frozen)" else "")

let () =
  let start = { owner = "Kim"; balance = 100; frozen = false } in
  let after = freeze (deposit start 50) in
  show start;
  show after
Kim: 100
Kim: 150 (frozen)

start is unchanged: functional update creates a new value. This makes it safe to keep old versions around (for undo, history, or sharing between threads).

Pattern matching on records

Records can be destructured in let, function parameters and match. Field punning lets you write { name; age } instead of { name = name; age = age }:

ocaml · try it yourself
type employee = { name : string; role : string; salary : int }

let describe { name; role; _ } = name ^ " works as " ^ role

let bonus e =
  match e with
  | { role = "engineer"; salary; _ } -> salary / 10
  | { salary; _ } when salary < 40_000 -> 2_000
  | _ -> 1_000

let () =
  let team =
    [ { name = "Ola"; role = "engineer"; salary = 72_000 };
      { name = "Raj"; role = "support"; salary = 38_000 };
      { name = "Eve"; role = "manager"; salary = 90_000 } ]
  in
  List.iter (fun e -> Printf.printf "%s, bonus %d\n" (describe e) (bonus e)) team
Ola works as engineer, bonus 7200
Raj works as support, bonus 2000
Eve works as manager, bonus 1000

_ at the end of a record pattern means "and other fields I don't care about".

Building records with punning

Punning also works when constructing a record from variables with the same names as the fields:

ocaml · try it yourself
type point = { x : float; y : float }

let make x y = { x; y }
let distance p q = sqrt (((q.x -. p.x) ** 2.) +. ((q.y -. p.y) ** 2.))
let midpoint p q = { x = (p.x +. q.x) /. 2.; y = (p.y +. q.y) /. 2. }

let () =
  let a = make 0. 0. and b = make 6. 8. in
  let m = midpoint a b in
  Printf.printf "distance %.1f, midpoint (%.1f, %.1f)\n" (distance a b) m.x m.y
distance 10.0, midpoint (3.0, 4.0)

Records in lists

Lists of records are a natural way to represent tables of data:

ocaml · try it yourself
type city = { name : string; country : string; population : int }

let () =
  let cities =
    [ { name = "Lagos"; country = "Nigeria"; population = 15_300_000 };
      { name = "Lyon"; country = "France"; population = 520_000 };
      { name = "Osaka"; country = "Japan"; population = 2_750_000 } ]
  in
  cities
  |> List.filter (fun c -> c.population > 1_000_000)
  |> List.sort (fun a b -> compare b.population a.population)
  |> List.iter (fun c -> Printf.printf "%-6s %-8s %9d\n" c.name c.country c.population)
Lagos  Nigeria   15300000
Osaka  Japan      2750000

Note: Records can also have mutable fields (mutable count : int) that you update with r.count <- 5. That is covered in the imperative section.

Test yourself

How do you create a copy of record p with field age set to 30?

  1. p.age = 30
  2. { p with age = 30 }
  3. p <- { age = 30 }
  4. copy p ~age:30

How does OCaml infer the type of fun r -> r.year?

  1. It cannot; an annotation is required
  2. From the field name year
  3. From the variable name r
  4. It assumes a tuple

What does { name; _ } mean as a pattern?

  1. A record with only a name field
  2. Bind the name field to name and ignore the other fields
  3. A syntax error
  4. A list of names