如何说服ocaml两个函子实例相等 [英] How to convince ocaml that two functor instantiations are equal

查看:75
本文介绍了如何说服ocaml两个函子实例相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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进行了参数化.然后,CD是独立的,并且E取决于CD.该代码无法编译,因为编译器无法确信EC.HashtblD.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.BD.B不共享相同的盐.因此,混合从C.B.HashD.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆