ocaml 中作为 module/functor 签名约束的变体类型

Variant types as module/functor signature constraints in ocaml

我正在尝试使用 modules/functors 进行更通用的代码设计。为了简化,我有两个接口:

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

但我显然不明白为什么。 将此类约束与变体一起使用的正确方法是什么?

PS:注意这个也被拒了

module OK2 (T: T1) : (T2 with type t = [ `X | `Y of T.t]) = struct
    type t = X | Y of T.t
end

在模块约束 with type t = ...,您不能编写类型定义,但可以编写类型表达式。

X | Y of T.t 是 variant 类型定义的 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