如何创建以自定义类型为键的 Hashtbl?

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

我正在尝试使用我编写的 node 类型创建一个 Hashtbl。

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

我想创建一个以节点作为指向浮点数的键的 Hashtbl,并且有这样的东西:

[((node), float))]

这是我迄今为止尝试过的方法:

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

连同:

module HashNodes = Hashtbl.Make(HashtblNodes);;

我不确定执行我之前解释的操作是否正确,而且我不知道如何用它创建 table。

请问我怎样才能做到这一点?

您的方法很有效(尽管请参阅对您关于 "you don't actually need to use the functor" 的问题的评论)。

从你在问题中的定义开始:

# 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.
#