Search code examples
ocamlhashtable

How to create a Hashtbl with a custom type as key?


I'm trying to create a Hashtbl with a node type I've written.

type position = float * float
type node = position * float

I'd like to create a Hashtbl with nodes as keys pointing to a float, and have something like this :

[((node), float))]

This is what I've tried so far :

module HashtblNodes =
   struct 
    type t = node
    let equal = ( = )
    let hash = Hashtbl.hash
   end;;

Along with :

module HashNodes = Hashtbl.Make(HashtblNodes);;

I'm not sure it's the right implementation to do what I explained before, plus I don't know how I could create the table with this.

How would I be able to do this please?


Solution

  • Your approach just works (though see a comment to your question about "you don't actually need to use the functor").

    Starting from your definitions in the question:

    # let tbl = HashNodes.create 1 ;;
    val tbl : '_weak2 HashNodes.t = <abstr>
    # let node1 = ((1.0, 2.0), 3.0);;
    val node1 : (float * float) * float = ((1., 2.), 3.)
    # let node2 = ((-1.0, -2.0), -3.0);;
    val node2 : (float * float) * float = ((-1., -2.), -3.)
    # HashNodes.add tbl node1 100.0;;
    - : unit = ()
    # HashNodes.add tbl node2 200.0;;
    - : unit = ()
    # HashNodes.find tbl ((1.0, 2.0), 3.0) ;;
    - : float = 100.
    #