Thomash
Thomash

Reputation: 6379

What's the difference between records and tuples in OCaml

Is there any difference between records and tuples that is not just a syntactic difference ?

Is there a performance difference ?

Is the implementation the same for tuples and records ?

Do you have examples of things that can be done using tuples but not with records (and conversely) ?

Upvotes: 6

Views: 2108

Answers (2)

gasche
gasche

Reputation: 31459

Floats fields in float-only records or arrays are stored unboxed, while no such optimization applies to tuples. If you are storing a lot of floats and only floats, it is important to use records -- and you can gain by splitting a mixed float/other datastructure to have an internal float-only record.

The other differences are at the type level, and were already described by Andreas -- records are generative while tuples pre-exist and have a structural semantics. If you want structural records with polymorphic accessors, you can use object types.

Upvotes: 12

Andreas Rossberg
Andreas Rossberg

Reputation: 36098

Modulo syntax they are almost the same. The main semantic difference is that tuples are structural types, while records are nominal types. That implies e.g. that records can be recursive while tuples cannot (at least not without the -rectypes option):

type t = {a : int, b : unit -> t}  (* fine *)
type u = int * (unit -> u)         (* error *)

Moreover, records can have mutable fields, tuples can't.

FWIW, in OCaml's sister language SML, tuples are records. That is, in SML (a,b,c) is just syntactic sugar for {1=a,2=b,3=c}, and records are structural types as well.

Upvotes: 21

Related Questions