Skip to content

Records

Devon Loehr edited this page Jun 20, 2019 · 2 revisions

Records in NV

NV provides support for OCaml-style records. Records are often more convenient for programmers than tuples, since they allow fields to be references by name rather than by position. However, NV records also have a couple of caveats. Internally, records are transformed into tuples.

Record Operations

NV supports the following operations related to records:

  • Type declaration: type rty = { a : int; b : bool; }

  • Creation: let r = { a = 0; b = true; } in ...

  • Projection: let x = r.a in ...

  • Pattern matching: match r with | { a = x; b = _; } -> ...

  • Selective updating: let r' = { r with b = false } in ...

Record Caveats

In order to ensure that we can easily perform type inference, we require that:

  • All record types are explicitly declared before use
  • No two record types contain the same label

Record Unrolling

Internally, records are handled by transforming them into tuples early on. This is referred to as record unrolling. The transformation is performed as follows:

  1. First, sort the labels within each record type
  2. Replace each record type with a tuple whose first element corresponds to the element with the smallest label, etc
  3. Replace record patterns and values with corresponding tuple patterns and values
  4. Replace record projections with a projection of the corresponding element of the tuple

Example

The program

  type rty = {a : int; b : bool; c : int;}

  let r = {a = 0; b = false; c = 7; } in
  r.c

gets transformed into

  type rty = int * bool * int

  let r = (0, false, 7) in
  match r with
  | (_, _, c) -> c
Clone this wiki locally