如何说服ocaml两个函子实例相等 [英] How to convince ocaml that two functor instantiations are equal
问题描述
假设我有许多模块,所有模块都用一种模块类型进行了参数化,并且彼此之间也具有依赖关系:
Suppose I have a number of modules that are all parameterized with one module type, and also have dependencies between each other:
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
进行了参数化.然后,C
和D
是独立的,并且E
取决于C
和D
.该代码无法编译,因为编译器无法确信E
,C.Hashtbl
和D.Hashtbl
内部是同一模块:
Here, everything is parameterized with AT
. Then, C
and D
are independent, and E
depends on C
and D
. This code does not compile, since the compiler is not convinced that inside E
, C.Hashtbl
and D.Hashtbl
are the same module:
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两个哈希集模块相同?
Is there a quick way to convince ocaml that the two hashset modules are the same?
推荐答案
类型检查器正确的是,两个Hashtbl
模块是不同的,不应混在一起:例如,考虑对B
模块进行稍加修改:
The typechecker is right that the two Hashtbl
modules are not the same and should not be mixed together: consider for instance a slightly modified B
module:
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.B
和D.B
不共享相同的盐.因此,混合从C.B.Hash
和D.B.Hash
派生的哈希表将是导致完全不稳定行为的错误.
Then the two instances C.B
and D.B
of the functor application F(A)
do not share the same salt. Consequently, mixing hash tables derived from C.B.Hash
and D.B.Hash
would be an error that leads to a completely erratic behavior.
这篇关于如何说服ocaml两个函子实例相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!