Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Newbie: declarations
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Sven LUTHER <luther@d...>
Subject: Re: [Caml-list] Newbie: declarations
On Tue, Jun 19, 2001 at 10:11:11AM +0200, Frédéric van der Plancke wrote:
> [Excuse-me if this is a duplicate. I haven't seen the previous instance
> of this message on the list yet, I think I sent it to the wrong address.
> This message contains additional thoughts anyway ;-)]
> 
> leary@nwlink.com wrote:
> > More to the point, is there a way to declare a record variable without
> > listing/initializing all the fields?  If yes, what are the default values?
> 
> You can create a default record and initialize new records from a copy
> of the default record like this:
> 
> type datarec = {
>          mutable name : string;
>          mutable color : string;
>          mutable value : int;
> }
> 
> let default_datarec = { name = "?"; color = "?"; value = 0; }   
> 
> let x = { default_datarec with value = 113 }
> let y = { default_datarec with name = "y"; color = "00FF00 FF00FF" }
> 
> Beware of aliasing though: the name string is mutable and is shared by
> all instances for which no specific name was given, so:
> 
> # x.name.[0] <- '!';;
> - : unit = ()
> # default_datarec.name;;
> - : string = "!"
> 

What about having a way to initialise struct types :

something like :

type datarec = {
         mutable name : string = "?";
         mutable color : string = "?";
         mutable value : int = 0;
}

And then you could do :

let x : datarec = { value = 113 }

or maybe 

let x = { type datarec with value = 113 } 

or something such ?

This would permit to do as above, but without the sharing problem.

But is it really usefull, i guess you could simply wrap the datatype in a
constructor, and not worry about such things :

type datarec = {
         mutable name : string;
         mutable color : string;
         mutable value : int;
}

let new_datarec n c v = {
  name = match n with None -> "?" | Some n -> n;
  color = match c with None -> "?" | Some c -> c;
  value = match v with None -> 0 | Some v -> v;
}

Then you could simply do :

let x = new_datarec None None (Some 113)
let y = new_datarec (Some "y") ("00FF00 FF00FF") None

Or even something more cleaner using labels and optional values.

Friendly,

Sven Luther

-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr