cod*_*nk1 1 ocaml functional-programming module functor
我想编写一个模块(在Ocaml 3.12中),能够将Variant类型定义为现有不同类型的聚合
它可以是0到N种类型,因此是变量列表或集合
它看起来像这样:
type newtype = Type0 of type0 | Type1 of type1 | ... | TypeN of typeN
Run Code Online (Sandbox Code Playgroud)
当然,我想将其创作分解
首先,我尝试创建一个由仿函数参数化的模块"Composite":
module Composite ( T0 : sig type t end ) ( T1 : sig type t end ) =
struct
type t = T0.t | T1.t
end
Run Code Online (Sandbox Code Playgroud)
第一个难点:如何将变量的变量列表传递给'Composite'模块?
这是一个很好的方法吗?
edit1:Variant允许定义一个XOR类型定义(它是T0或T1,但不是两者); 如何定义OR类型定义(可以是T0或T1或两者)?
如果想要一个"平面"复合类型并获得构造函数的联合,唯一的方法是使用多态变体(如注释中的@lukstafi所述),但在这种情况下,t1和t2不能是抽象的:
type t1 = [ `A of int | `B of string | `C of float ]
type t2 = [ `B of string | `C of float | `D of char ]
type t3 = [ t1 | t2 ]
Run Code Online (Sandbox Code Playgroud)
如果你真的想要使用模块,你必须松开你的平面表示,因此你将有一个不相交的联合:
module Composite ( T0 : sig type t end ) ( T1 : sig type t end ) =
struct
type t = T0 of T0.t | T1 of T1.t
end
Run Code Online (Sandbox Code Playgroud)