What's the difference between records and tuples in OCaml

喜夏-厌秋 提交于 2019-12-07 06:22:48

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10481910/whats-the-difference-between-records-and-tuples-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!