![](/img/trans.png)
[英]How would I write a generic function to handle multiple record types in ReScript?
[英]How do I implement hash functions for arbitrary record types in ReScript?
我是第一次探索 ReScript。 我想使用記錄類型作為我的密鑰類型來構建 hashmap,並且我正在尋找有關實施 hash function 的指導。
這是我的 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
function 的任何指導。
在其他編程語言(例如 Java)中,希望您實現hashCode()
,有無處不在的工具來支持組合現有的 hash 函數。
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
模塊中有一個內置的多態 hash function :
let hash: 'a => int
這來自 ReScript 繼承的 OCaml 標准庫。 您可以在此處找到文檔: https://docs.ocaml.pro/html/LIBRARY.stdlib@ocaml-base-compiler.4.10.0/Stdlib/Hashtbl/index.html#val-hash
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.