8.18 Inline records

(Introduced in OCaml 4.03)

constr-args::=
record-decl

The arguments of sum-type constructors can now be defined using thesame syntax as records. Mutable and polymorphic fields are allowed.GADT syntax is supported. Attributes can be specified on individualfields.

Syntactically, building or matching constructors with such an inlinerecord argument is similar to working with a unary constructor whoseunique argument is a declared record type. A pattern can bindthe inline record as a pseudo-value, but the record cannot escape thescope of the binding and can only be used with the dot-notation toextract or modify fields or to build new constructor values.

  1. type t =
  2. | Point of {width: int; mutable x: float; mutable y: float}
  3. | Other
  4. let v = Point {width = 10; x = 0.; y = 0.}
  5. let scale l = function
  6. | Point p -> Point {p with x = l *. p.x; y = l *. p.y}
  7. | Other -> Other
  8. let print = function
  9. | Point {x; y; _} -> Printf.printf "%f/%f" x y
  10. | Other -> ()
  11. let reset = function
  12. | Point p -> p.x <- 0.; p.y <- 0.
  13. | Other -> ()
  14.  
  1. let invalid = function
  2. | Point p -> p
  3. Error: This form is not allowed as the type of the inlined record could escape.