编译这个程序时:
module type Inc =
sig
type t
val inc : t -> t
end
module type Dec =
sig
type t
val dec : t -> t
end
module Merger (I : Inc) (D : Dec with type t = I.t) =
struct
let merge x = x |> I.inc |> D.dec
end
module IntInc : Inc =
struct
type t = int
let inc x = x + 10
end
module IntDec : Dec =
struct
type t = int
let dec x = x - 8
end
module Combiner = Merger (IntInc) (IntDec)
我收到以下错误:
File "simple.ml", line 30, characters 35-41:
Error: Signature mismatch:
Modules do not match:
sig type t = IntDec.t val dec : t -> t end
is not included in
sig type t = IntInc.t val dec : t -> t end
Type declarations do not match:
type t = IntDec.t
is not included in
type t = IntInc.t
File "simple.ml", line 13, characters 38-50: Expected declaration
File "simple.ml", line 9, characters 13-14: Actual declaration
我以为D : Dec with type t = I.t
约束将确保D.t = I.t
。为什么不是这样呢?
更有趣的是,当我删除module Combiner = Merger (IntInc) (IntDec)
行它编译没有错误。
我的问题是:我做错了什么?
你的定义Merger
with 约束是完全正确的,这就是为什么该部分编译时没有错误。
正如你所说,唯一不能编译的部分是module Combiner = Merger (IntInc) (IntDec)
。这是因为,据 OCaml 所知,约束IntInt.t = IntDec.t
没有满足。原因是 OCaml 不知道IntInt.t
and IntDec.t
are int
。它所知道的是IntInt : Inc
and IntDec : Dec
- 其他一切都是模块的私有细节。
要解决此问题,您可以将模块的标头更改为IntInt : (Inc with type t = int)
and IntDec : (Dec with type t = int)
,制作类型t
模块公共接口的一部分而不是私有细节,允许 OCaml 在解决模块的约束时使用该信息Merger
函子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)