title: Copy mutable data structure and preserve sharing?
body: <p>Suppose that I have a <code>int ref list</code> and I want to make a copy of it. One option is the following:</p>
  <pre class="lang-ml prettyprint-override"><code>let copy_ref_list : int ref list -&gt; int ref list =
    List.map (fun x -&gt; ref !x)
  </code></pre>
  <p>However, this losing sharing within the nodes. For example,</p>
  <pre class="lang-ml prettyprint-override"><code>let v =
    let x = ref 0 in
    copy_ref_list [x; x; x] (* creates three copies of [x] *)
  </code></pre>
  <p>Is there an efficient way to implement a function that would produce only one copy of <code>x</code> above, so that the result is the same as:</p>
  <pre class="lang-ml prettyprint-override"><code>let copy_of_v =
    let x = ref 0 in
    [x; x; x]
  </code></pre>
  <p>It seems like I can use a memoized copy function with a <code>Hashtbl</code>, but does that give the right behavior on references?</p>
  <pre class="lang-ml prettyprint-override"><code>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 -&gt;
        let y = ref !x in
        let () = Hashtbl.add memo x y in
        y
    in
    List.map copy
  </code></pre>