Suppose that I have a int ref list and I want to make a copy of it. One option is the following:
let copy_ref_list : int ref list -> int ref list =
List.map (fun x -> ref !x)
However, this losing sharing within the nodes. For example,
let v =
let x = ref 0 in
copy_ref_list [x; x; x] (* creates three copies of [x] *)
Is there an efficient way to implement a function that would produce only one copy of x above, so that the result is the same as:
let copy_of_v =
let x = ref 0 in
[x; x; x]
It seems like I can use a memoized copy function with a Hashtbl, but does that give the right behavior on references?
let copy_ref_list (x : int ref list) : int ref list =
let memo = Hashtbl.create 17 in
let copy x =
try Hashtbl.find memo x
with Not_found ->
let y = ref !x in
let () = Hashtbl.add memo x y in
y
in
List.map copy