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