ocaml 中的哈希表
是否可以在 Ocaml 中的同一个哈希表 (Hashtbl
) 中存储不同类型?哈希表真的仅限于一种类型吗?
Is it possible to store different types in the same hashtable (Hashtbl
) in Ocaml? Are hashtables really restricted to just one type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,每个表的哈希表条目仅限于一种类型。这实际上是一个关于 OCaml 类型系统的问题,而不是关于哈希表的问题。如果要求哈希表中的事物具有相同的类型似乎很奇怪,那么在列表中又如何呢?
如果不知道您要解决的问题,就很难知道该提出什么建议。然而,常见的做法是创建一个代数类型,该代数类型对于您正在处理的每种类型都有一个变体:
(string, alg) 类型的值 Hashtbl.t 将存储整数和浮点数,使用字符串作为查找键。
当您习惯了 OCaml 灵活且强大的类型之后,就很难再回到没有它的系统。
Yes, hash tables entries are restricted to one type for each table. This is really a question about the OCaml type sytem and not about hash tables. If it seems odd to require things to be the same type in a hash table, how about in a list?
Without knowing the problem you're solving, it's hard to know what to suggest. However, a common thing to do is to create an algebraic type that has one variant for each of the types you're dealing with:
A value of type (string, alg) Hashtbl.t would store ints and floats, using a string as the lookup key.
After you get used to the flexible and strong typing of OCaml, it's hard to go back to systems without it.