简体   繁体   中英

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) ?

Modulo syntax they are almost the same. The main semantic difference is that tuples are structural types, while records are nominal types. That implies eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM