Ocaml 参数化模块类型
我试图构建一个相互依赖的模块类型层次结构。在Coq中,我可以这样写:Ocaml 参数化模块类型,ocaml,Ocaml,我试图构建一个相互依赖的模块类型层次结构。在Coq中,我可以这样写: Module Type Foo. Parameter t:Type. End Foo. Module Type Bar1 (T:Foo). Parameter f1: T.t -> T.t. End Bar1. Module Type Bar2 (T:Foo). Parameter f2: T.t -> T.t. End Bar2. Module Ex (F:Foo) (B1: Bar1 F) (
Module Type Foo.
Parameter t:Type.
End Foo.
Module Type Bar1 (T:Foo).
Parameter f1: T.t -> T.t.
End Bar1.
Module Type Bar2 (T:Foo).
Parameter f2: T.t -> T.t.
End Bar2.
Module Ex (F:Foo) (B1: Bar1 F) (B2:Bar2 F).
End Ex.
我将如何用OCaml表示它 模块类型不接受参数。但是,此特定模式可以用类型表示为
:
module type FOO = sig
type t
end
module type BAR1 = sig
type t
val f1 : t -> t
end
module type BAR2 = sig
type t
val f2 : t -> t
end
module Ex (F:FOO) (B1 : BAR1 with type t = F.t) (B1 : BAR2 with type t = F.t) = struct
end
不幸的是,Ocaml不直接支持参数化模块类型。但是,您可以通过围绕它们包装参数化模块来模拟它们:
module type Foo =
sig
type t
end
module Bar (X : Foo) =
struct
module type T =
sig
val f : X.t -> X.t
end
end
module Ex (F : Foo) (B : Bar(F).T) = ...
稍显笨拙,但效果相同。为了详细说明gsg的答案,如果您有更复杂的Foo
模块类型,您可以将与模块一起使用,而不是与类型一起使用,并且在与条形两种类型中都有模块规范,如以下示例所示:
module type Foo =
sig
type t
end
module type Bar1 = sig
module F: Foo
val f1: F.t -> F.t
end
module type Bar2 = sig
module F: Foo
val f2: F.t -> F.t
end
module Ex (F: Foo) (B1: Bar1 with module F = F) (B2: Bar2 with module F = F) =
struct
let f3 x = B2.f2 (B1.f1 x)
end
module Bar1_impl (F: Foo): Bar1 with module F = F = struct
module F = F
let f1 x = x
end
module Bar2_impl (F: Foo): Bar2 with module F = F = struct
module F = F
let f2 x = x
end
module F: Foo with type t = int = struct type t = int end
module M = Ex(F)(Bar1_impl(F))(Bar2_impl(F))
let x = M.f3 0;;
如果我在FOO中有多个定义,它可能会变得有点笨拙。我也看过“Include FOO”语法。不确定它是否有帮助……我喜欢这个解决方案。谢谢!