Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between records and tuples in OCaml

Tags:

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

like image 508
Thomash Avatar asked May 07 '12 12:05

Thomash


People also ask

What is the difference between tuple and record?

Records are similar to tuples, in that they group together various data elements. A record has fields, and these are named. While tuples are an ordered collection of data values, a tuple is an unordered collection of labeled data values.

What is a tuple in OCaml?

Every function in OCaml takes exactly one value and returns exactly one result. For instance, our squareRoot function takes one float value and returns one float value. The advantage of always taking one argument and returning one result is that the language is extremely uniform.

What is :: In OCaml?

Note that :: is technically a type constructor which is why you can use it in both patterns and expressions.


1 Answers

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.

like image 119
Andreas Rossberg Avatar answered Nov 15 '22 11:11

Andreas Rossberg