Version française
Home     About     Download     Resources     Contact us    
Browse thread
different records, same field name?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: DooMeeR <d@d...>
Subject: Re: [Caml-list] different records, same field name?
mfmorss@aep.com a écrit :
> I have not used OCaml, just done some reading about it and toyed with the 
> toplevel to see if it might be a useful tool here.  I have "Practical 
> OCaml," which unfortunately is a rather wretched reference.
> 
> In any case, is it possible to define and use different types of records, 
> which nevertheless share some field names?  I have had difficulty doing 
> this in the toplevel.

Sharing names for record labels, as well as for variant tags, is not a 
good idea. Indeed, only the last name is remembered (as for everything 
in OCaml), so the type system will infer the last type which has this label.

One way to separate names is to use modules, for instance:

module People = struct
   type t = {
     name: string;
     age: int;
   }
end;;

Then you can use labels People.name and People.age, for instance:

let x = {
   People.name = "x";
   age = 69;
};;

Notice how, when defining this variant, you don't have to use "People." 
for every label.

x.People.name

The toplevel gives you:
- : string = "x"

If you know you won't have any name clash, you can open module People 
and you won't have to use "People." everytime:

open People;;

let x = {
   name = "x";
   age = 69;
};;

-- 
Romain Bardou