Reading — step 1 of 5
Learn
~1 min readRecords and Modules
OCaml records are named-field tuples — like structs but immutable by default.
type person = {
name : string;
age : int;
}
let ada = { name = "Ada"; age = 36 }
let () = print_endline ada.name (* "Ada" *)
Record update — return a new record with one field changed:
let older = { ada with age = 37 }
Pattern match on records:
let describe = function
| { name; age } when age >= 65 -> Printf.sprintf "%s, retired" name
| { name = "Admin"; _ } -> "administrator"
| { name; _ } -> name
The _ pattern says "ignore the rest of the fields."
Mutable fields with mutable keyword:
type counter = { mutable count : int }
let c = { count = 0 }
c.count <- c.count + 1 (* mutation: <- *)
Functional record update is preferred unless mutation is essential. For occasional mutable state, mutable fields are fine; for serious mutation, use ref (next).
Record disambiguation — when two record types share field names, OCaml uses the first matching type. Annotate explicitly when needed:
let p : person = { name = "Ada"; age = 36 }
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…