English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Shallow copy of a record
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-01-22 (06:50)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Shallow copy of a record
From: Chris King <colanderman@gmail.com>

> Maybe I missed it in the docs, but is there a way to create a shallow
> copy of a record without modifying any of its contents?  I know
> there's the {foo with a=b} construct, but this only works with at
> least one assignment; I want to create an unmodified copy of the
> record (akin to the {< >} construct for objects).

This does not exist, and with good reason: there is no way in the type
system to define a function which works on all records, but only
records. So to do the copy you need to know at least one of the labels
of the record, which in turn gives you its type.

Another approach, which is potentially unsafe, is to use the Obj.dup
function. You can make it a bit safer by ensuring (dynamically) that
you only copy caml blocks or values:

  let copy (v : 'a) : 'a =
    let obj = Obj.repr v in
    if Obj.is_int obj then v
    else if Obj.is_block obj && let tag = Obj.tag obj in
            tag < Obj.lazy_tag || tag = Obj.double_array_tag
    then Obj.obj (Obj.dup obj)
    else invalid_arg "shallow copy"

Jacques Garrigue