OCaml Matching record fields


Example

Pattern matching can be used to deconstruct records. We illustrate this with a record type representing locations in a text file, e.g. the source code of a program.

type location = {
  filename : string;
  line: int;
  column: int;
  offset: int;
}

A value x of type location can be deconstructed like this:

let { filename; line; column; offset; } = x

A similar syntax can be used to define functions, for instance a function to print locations:

let print_location { filename; line; column; offset; } =
  Printf.printf "%s: %d: %d" filename line column

or alternatively

let print_location = function { filename; line; column; offset; } ->
  Printf.printf "%s: %d: %d" filename line column

Patterns matching records do not need to mention all fields of a record. Since the function does not use the offset field, we can leave it out:

let print_location { filename; line; column; } =
  Printf.printf "%s: %d: %d" filename line column

When the record is defined in a module, it is enough to qualify the first field occurring in the pattern:

module Location =
struct
  type t = {
      filename : string;
      line: int;
      column: int;
      offset: int;
    }
end

let print_location { Location.filename; line; column; } =
  Printf.printf "%s: %d: %d" filename line column