Browse thread
[Caml-list] Newbie: declarations
-
leary@n...
- Vitaly Lugovsky
- David Fox
- Frédéric van der Plancke
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Frédéric van der Plancke <fvdp@d...> |
| Subject: | Re: [Caml-list] Newbie: declarations |
[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 = "!"
Furthermore "someone" may directly modify the default_datarec in your
back.
This is not the safest way to do it.
Unless you do this:
let default_datarec () =
{
name = String.copy "?"; (* Need to copy in order to avoid aliasing *)
color = String.copy "?";
value = 0;
}
let x =
let d = default_datarec () in
{ d with value = 113 }
One can't write { default_datarec () with value = 113 } ...
And BTW, I like Python's immutable strings ! (Wouldn't be long to
implement an immutable-strings module in OCaml though.)
/Frederic vdP
-------------------
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