1

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

module type T1 = sig type t end;;
module type T2 = sig type t end;;

我想T2.t用一个基于T1.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
4

1 回答 1

2

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

X | Y of T.t是变体类型定义的 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
于 2017-12-14T07:44:21.153 回答