gpt4 book ai didi

ocaml - 如何让 ocaml 相信两个仿函数实例化是相等的

转载 作者:行者123 更新时间:2023-12-02 20:31:13 27 4
gpt4 key购买 nike

假设我有许多模块,它们都使用一种模块类型进行参数化,并且彼此之间也具有依赖关系:

module type AT = sig  
end

module B(A: AT) = struct
module Hash = struct
type t = int
let equal b1 b2 = b1 = b2
let hash b = b
end
end

module C(A: AT) = struct
module B = B(A)
module Hashtbl = Hashtbl.Make(B.Hash)

let make () = Hashtbl.create 16
end

module D(A: AT) = struct
module B = B(A)
module Hashtbl = Hashtbl.Make(B.Hash)

let use ht =
Hashtbl.clear ht
end

module E(A: AT) = struct
module C = C(A)
module D = D(A)

let f () =
D.use (C.make ())
end

在这里,所有内容都通过 AT 进行参数化。那么,CD 是独立的,E 依赖于 CD 。此代码无法编译,因为编译器不相信 EC.HashtblD.Hashtbl 内部是同一模块:

File "xxxx.ml", line xx, characters xx-xx:
Error: This expression has type 'a C.Hashtbl.t = 'a Hashtbl.Make(C.B.Hash).t
but an expression was expected of type
'b D.Hashtbl.t = 'b Hashtbl.Make(D.B.Hash).t

有没有一种快速方法可以让 ocaml 相信两个哈希集模块是相同的?

最佳答案

类型检查器是正确的,两个 Hashtbl 模块不相同,不应混合在一起:例如考虑稍微修改的 B 模块:

module B(A: AT) = struct
module Hash = struct
let y = Random.int 10
type t = int
let equal b1 b2 = b1 = b2
let hash b = b + y
end
end

那么仿函数应用 F(A) 的两个实例 C.BD.B 不共享相同的 salt。因此,混合从 C.B.HashD.B.Hash 派生的哈希表将是一个错误,会导致完全不稳定的行为。

关于ocaml - 如何让 ocaml 相信两个仿函数实例化是相等的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com