ocamlhashtabledouble-hashing

Ocaml double hash table


I have been looking for a way to use a double hash table in Ocaml, but cannot find it. What I want to do is something like:

Hash: (("a",1), ("b",2), ...) , where all the mentioned elements are not repeated, for instance, "a" will not appear again, nor 2.

So if I find an array like [1, "b", 2, "a",...] I can replace those appearings of the numbers and letters by its keys or values: ["a",2,"b",1,...] .

Thanks!


Solution

  • The library containers-data has CCBijections.

    If you want a mutable version, you can pair two hash tables with

    module Table: sig
      type (!'left, !'right) t
      (* or before OCaml 4.12:
         type (!'left, !'right) t
      *) 
      val add: 'left ->'right -> ('left,'right) t -> unit
      ...
    end = struct
      type ('a,'b) t = {left:('a,'b) Hashtbl.t; right:('b,'a) Hashtbl.t }
      let add left right tbl =
        Hashtbl.add tbl.left left right;
        Hashtbl.add tbl.right right left
        ...
    end