Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 40 ยท Lists, Arrays and Records

Records in OCaml

Define your own record types with named fields, create and read records, copy with the with syntax, match on records, use field punning, mutable fields and records with type parameters.

A record groups named fields into one value, like a struct in C or Go or an object with fixed properties in JavaScript. Unlike tuples, the fields have names, so code stays readable as data grows. Unlike lists and arrays, each field can have a different type. Records need a type declaration before you use them.

Declaring and creating records

OCAML
type point = { x : float; y : float }

type person = {
  name : string;
  age : int;
  email : string option;
}

A record type lists field : type separated by semicolons. Create a value by giving every field:

OCAML
let origin = { x = 0.0; y = 0.0 }
let ada = { name = "Ada"; age = 36; email = Some "[email protected]" }

The compiler infers the record type from the field names. All fields must be given; there are no defaults and no uninitialized fields.

OCAML
# origin;;
- : point = {x = 0.; y = 0.}

Reading fields

Use dot notation:

OCAML
# ada.name;;
- : string = "Ada"
# ada.age + 1;;
- : int = 37

let distance_from_origin p = sqrt (p.x ** 2. +. p.y ** 2.)

Functional update with with

Records are immutable by default. To "change" a field, create a copy with some fields replaced:

OCAML
let older = { ada with age = ada.age + 1 }
let moved = { origin with x = 5.0 }

{ r with f = v } copies all fields from r except the ones you list. The original is untouched; unchanged fields are shared. You can replace several at once: { ada with age = 37; email = None }.

Pattern matching on records

You can take records apart in let, function parameters and match:

OCAML
let describe { name; age; _ } =
  Printf.sprintf "%s is %d" name age

let is_adult { age; _ } = age >= 18

let first_name p =
  match p with
  | { name = "Ada"; _ } -> "the countess"
  | { name; _ } -> name

{ name; age; _ } uses field punning: name stands for name = name, binding a variable named like the field. The _ says "I ignore the other fields"; without it, you get a warning if you forgot some. The same punning works when you create records: { name; age; email } if variables with those names exist.

Mutable fields

Mark a field mutable to allow in-place updates with <-:

OCAML
type counter = { mutable count : int; label : string }

let c = { count = 0; label = "clicks" }
let () = c.count <- c.count + 1
let () = c.count <- c.count + 1
(* c.count is now 2 *)

Only the fields marked mutable can be changed; label cannot. Prefer immutable records unless you need shared mutable state (for example, a counter used from several functions). More on this in the imperative-features chapter.

Records in lists and functions

OCAML
let people = [
  { name = "Ada"; age = 36; email = None };
  { name = "Linus"; age = 28; email = None };
  { name = "Grace"; age = 85; email = None };
]

let names = List.map (fun p -> p.name) people
let adults = List.filter (fun p -> p.age >= 30) people
let oldest =
  List.fold_left (fun best p -> if p.age > best.age then p else best)
    (List.hd people) people
let sorted = List.sort (fun a b -> compare a.age b.age) people
OCAML
# names;;
- : string list = ["Ada"; "Linus"; "Grace"]

Type-directed disambiguation

If two record types share a field name, the latest declared type wins unless the compiler can see which one you mean:

OCAML
type user = { id : int; name : string }
type product = { id : int; title : string }

let u = { id = 1; name = "Ada" }      (* user, from the other field *)
let get_id p = p.id                   (* defaults to product, the last one *)
let get_user_id (u : user) = u.id     (* an annotation picks user *)

For clarity, either give fields distinct names (user_id, product_id) or annotate. Another good option is to put each type in its own module, as covered in the modules chapter.

Parameterized records

Records may have type parameters, as lists do:

OCAML
type 'a pair = { first : 'a; second : 'a }

let swap p = { first = p.second; second = p.first }

swap has type 'a pair -> 'a pair.

Printing records

OCaml does not print records automatically in programs (the toplevel does so for you). Write a function with Printf:

OCAML
let to_string p = Printf.sprintf "(%.1f, %.1f)" p.x p.y

let () = print_endline (to_string { x = 1.5; y = 2.0 })
(* (1.5, 2.0) *)

%f is a float, %d an int, %s a string; %.1f rounds to one decimal. A derive-style PPX such as ppx_deriving.show can generate printers; see the tooling chapter.

Records versus tuples

tuple record
declaration none type t = { ... }
access pattern matching, fst/snd field names
readability low for many parts high
good for quick returns of 2 or 3 values any real data model

A stand-in: functional update

JavaScript's object spread works like { r with ... }. The stand-in also shows the difference between an immutable update and a mutable field.

JS Stand-in: records, with-update and mutable fields

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. How do you create a copy of ada with age 37?

    { r with field = v } creates a new record with that field replaced.
  2. 2. What must you do to modify a field in place with <-?

    Only fields declared with the mutable keyword can be assigned.
  3. 3. What does { name; age; _ } mean in a pattern?

    Field punning binds variables named like the fields, and _ ignores the rest.
  4. 4. Why use records instead of tuples for bigger data?

    Named fields document the meaning of each part and avoid position mistakes.

Summary

  • Declare a record with type t = { field : type; ... } and create it with all fields.
  • Read fields with r.field; copy-with-changes using { r with field = v }.
  • Destructure with patterns, including punning and _.
  • mutable fields allow r.field <- v; the default is immutable.
  • Resolve field-name clashes with distinct names, annotations or modules.

Next: Variant Types: Modelling Choices with Constructors