我是第一次探索ReScript。我想使用记录类型作为密钥类型来构建一个哈希映射,我正在寻找实现哈希函数的指导。
这是我的ReScript代码:
type pointer = { id: string, table: string, spaceId: option<string> }
module PointerHash = Belt.Id.MakeHashable({
type t = pointer
let hash = a => 0 /* How do I implement this? */
let eq = (a, b) =>
a.id == b.id &&
a.table == b.table &&
switch (a.spaceId, b.spaceId) {
| (Some(aid), Some(bid)) => aid == bid
| _ => false
}
})
我浏览了文档并在网上搜索,但没有找到任何关于如何实现hash
功能的指导。
在其他编程语言中,例如Java,希望您实现hashCode()
,有一些无处不在的工具可以支持组合现有的散列函数。
class Pointer {
public final id: String
public final table: String
public final @Nullable spaceId: String
/* omitting constructor, etc */
@Override
public int hashCode() {
// Standard helper for implementing hashCode()
return Objects.hash(this.id, this.table, this.spaceId);
}
}
我查看了Belt.HashMapString的实现,看看是否有任何提示,看起来HashMapString使用了caml_hash_mix_string
:
external caml_hash_mix_string : seed -> string -> seed = "caml_hash_mix_string"
external final_mix : seed -> seed = "caml_hash_final_mix"
let hash (s : key) =
final_mix (caml_hash_mix_string 0 s )
访问和撰写";散列混合";功能?ReScript提供了一个不错的界面,可以使用这些吗?
Hashtbl
模块中有一个内置的多态散列函数:
let hash: 'a => int
这来自ReScript继承的OCaml标准库。您可以在那里找到文档:https://docs.ocaml.pro/html/LIBRARY.stdlib@ocaml基本编译器4.10.0/Stdlib/Hashtbl/index.html#val hash