首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ReScript中为任意记录类型实现哈希函数?

如何在ReScript中为任意记录类型实现哈希函数?
EN

Stack Overflow用户
提问于 2021-05-09 01:46:23
回答 1查看 86关注 0票数 2

我是第一次探索ReScript。我想使用一个记录类型作为我的键类型来构建一个散列映射,并且我正在寻找关于实现散列函数的指导。

下面是我的ReScript代码:

代码语言:javascript
复制
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()的编程语言中,有一些普遍的工具可以支持组合现有的哈希函数。

代码语言:javascript
复制
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

代码语言:javascript
复制
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提供的很好的界面?

EN

回答 1

Stack Overflow用户

发布于 2021-05-09 02:03:47

Hashtbl模块中有一个内置的多态散列函数:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67450498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档