data-structuresmergeocamlhashtable

Ocaml merge Hash tables


I would like to merge two same-type hash tables in Ocaml, so that the information of both of them gets stored in a single table. Imagine, something like:

  type tabType = (string, variable) Hashtbl.t

  let tabExample:tabType = Hashtbl.create 1000 in
  let tab1 = do_stuff tabExample a true in
  let tab2 = do_stuff tabExample a false in
  let tabFinal = tab1@tab2

Any idea?


Solution

  • If tab1 can be overwritten and the entries in tab2 should replace the one in tab1, this is just a fold:

      let merge ~into:tab1 tab2 =
        Hashtbl.fold (fun key elt () -> Hashtbl.replace tab1 key elt) tab2 ();
        tab1