typestar

Records in OCaml

Immutable named bundles with structural equality built in.

(* Records are immutable named bundles; with copies and updates. *)
type sighting = { species : string; count : int; pool : string }

let star = { species = "sea star"; count = 3; pool = "ledge" }

(* The with syntax copies, changing only what you name. *)
let more = { star with count = 5 }

let () =
  Printf.printf "%s: %d in the %s pool\n" star.species star.count
    star.pool;
  Printf.printf "Recount: %d (original still %d)\n" more.count
    star.count;
  (* Structural equality comes free. *)
  Printf.printf "Same sighting? %b\n" (star = { more with count = 3 })

How it works

  1. type sighting = { ... } declares the shape; construction names fields.
  2. { star with count = 5 } copies, changing one field.
  3. = compares by value, not by reference.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
556
Tokens
107
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 3 in Types, step 15 of 29 in Language basics.

← Previous Next →

Records in other languages