OCaml函子采用多态变体类型

int*_*nt3 6 ocaml

尝试编译

module F (M : sig
  type t = [> `Foo ]
end) = struct
  type t = [ M.t | `Bar ]
end
Run Code Online (Sandbox Code Playgroud)

让我

Error: A type variable is unbound in this type declaration.
In type [> `Foo ] as 'a the variable 'a is unbound
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

cam*_*ter 6

type t = [> `Foo]无效,因为[> `Foo]它是开放类型,并且隐式包含类型变量。由于RHS具有未在LHS中量化的类型变量,因此拒绝该定义的方式与拒绝以下类型定义的方式一样:

type t = 'a list
Run Code Online (Sandbox Code Playgroud)

您必须将其关闭:

type t = [ `Foo ]
Run Code Online (Sandbox Code Playgroud)

或量化类型变量:

type 'a t = [> `Foo] as 'a
Run Code Online (Sandbox Code Playgroud)

相当于

type 'a t = 'a constraint 'a = [> `Foo]
Run Code Online (Sandbox Code Playgroud)