Single-field records

Just out of curiosity, does OCaml optimize single-field records? I.e., are the types

type t = { field: some_type }

and

type t = some_type

implemented in the same way?

1 Like

This is not enabled by default, but recent version of OCaml (≥4.04) can optimize this pattern either by adding an attribute annotation

type t = { field: some_type } [@@unboxed]

or using the global -unboxed-types compiler option.
This is also works for variants with a single constructor:

 type t = Constructor of some_type [@@unboxed]

p.s: There are some corner cases where this optimization is not available due to inteferences with some of the float based optimizations, but the compiler will emit a warning in such cases:

type t = Any: 'a -> t [@@unboxed] 

Error: This type cannot be unboxed because it might contain both float and non-float values. You should annotate it with [@@ocaml.boxed].

7 Likes

What’s the rational behind not making this the default?

Backwards compatibility with C code that assumes the non-optimised representation.

6 Likes