Module ocaml中作为模块/函子签名约束的变量类型
我试图使用模块/函子来进行更通用的代码设计。为了简化,我有两个接口:Module ocaml中作为模块/函子签名约束的变量类型,module,ocaml,functor,variant,polymorphic-variants,Module,Ocaml,Functor,Variant,Polymorphic Variants,我试图使用模块/函子来进行更通用的代码设计。为了简化,我有两个接口: module type T1 = sig type t end;; module type T2 = sig type t end;; 我想用基于T1.t的变量类型实例化T2.t (* simple example, this one is accepted *) module OK (T: T1) : (T2 with type t = T.t) = struct type t = T.t end;; (* using a
module type T1 = sig type t end;;
module type T2 = sig type t end;;
我想用基于T1.t
的变量类型实例化T2.t
(* simple example, this one is accepted *)
module OK (T: T1) : (T2 with type t = T.t) = struct type t = T.t end;;
(* using a variant type, this one is rejected *)
module KO (T: T1) : (T2 with type t = X | Y of T.t) = struct
type t = X | Y of T.t
end
在后者中,我得到以下错误:
Unbound module X
Syntax error inside `module' after unclosed (, expected `.'
但是,如果我使用多态变体,似乎可以接受:
module OK2 (T: T1) : (T2 with type t = [ `X | `Y of T.t]) = struct
type t = [ `X | `Y of T.t ]
end
但我显然不明白为什么。
对变量使用此类约束的正确方法是什么
注:请注意,这一个也被拒绝
module OK2 (T: T1) : (T2 with type t = [ `X | `Y of T.t]) = struct
type t = X | Y of T.t
end
在类型为t=…的模块约束
中,您不能编写类型定义,只能编写类型表达式
T.T的
X | Y是一个变体类型定义的rhs,因此作为语法错误被拒绝。另一方面,[`X |`Y of T.T]
是一个类型表达式
如果您不确定正常变体和多态变体之间的差异,请查看OCaml书籍或参考手册
你想写的可能是
module type T3 = sig
type t'
type t = X | Y of t'
end
module KOX (T: T1) : (T3 with type t' := T.t) = struct
type t = X | Y of T.t
end
谢谢,我会尽力调查的。我找到了几个关于正常/多态变异的信息来源,但很难看出哪一个是最新的。您有什么可以推荐的吗?OCaml手册将是最新信息的最终来源:它们既有优点也有缺点,这就是为什么它们都存在于该语言中。如果不确定,请坚持使用普通车型。