【问题标题】:How do I implement hash functions for arbitrary record types in ReScript?如何在 ReScript 中为任意记录类型实现哈希函数?
【发布时间】:2021-05-09 02:03:46
【问题描述】:

我是第一次探索 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 函数的任何指导。

在期望您实现hashCode() 的其他编程语言(例如Java)中,有无处不在的工具来支持组合现有的散列函数。

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);
  }
}

我看了implementation of 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 的漂亮界面获得?

【问题讨论】:

    标签: reason bucklescript rescript


    【解决方案1】:

    Hashtbl 模块中有一个内置的多态哈希函数:

    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

    【讨论】:

    • Belt 中是否有等价物?
    • @AlllainLalonde 没有,但由于 Hashtbl.hash 在 ReScript 中是开箱即用的,因此您不需要在 Belt 中使用等效项。
    猜你喜欢
    • 2016-03-25
    • 2011-01-19
    • 2022-01-07
    • 2015-07-06
    • 2010-09-06
    • 2015-02-02
    • 2016-03-05
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多