我怎样才能定义一个 Set
在 OCaml 中也可以包含其类型的元素?
为了解释这个问题,我有很多数据类型的类型声明,比如
type value =
Nil
| Int of int
| Float of float
| Complex of Complex.t
| String of string
| Regexp of regexp
| Char of char
| Bool of bool
| Range of (int*int) list
| Tuple of value array
| Lambda of code
| Set of ValueSet.t (* this isn't allowed in my case since module is declared later*)
此外,我为
ValueSet
声明了一个具体模块稍后在同一个文件中:module ValueSet = Set.Make(struct type t = value let compare = Pervasives.compare end)
问题是
ValueSet
有 value
因为它是 elt 类型,但 value
可以是 ValueSet
所以我在尝试编译它时遇到了麻烦。所有这些声明都包含在一个名为
types.ml
的文件中。 (它有自己的接口(interface) types.mli
但没有任何 ValueSet
模块 decl,因为我不确定它是否可能)。这个问题可以通过某种方式解决吗?
最佳答案
您可以使用递归模块。 Language manual使用完全相同的递归集类型示例来说明此语言功能。以下是相关摘录。
A typical example of a recursive module definition is:
module rec A : sig type t = Leaf of string | Node of ASet.t val compare: t -> t -> int end = struct type t = Leaf of string | Node of ASet.t let compare t1 t2 = match (t1, t2) with (Leaf s1, Leaf s2) -> Pervasives.compare s1 s2 | (Leaf _, Node _) -> 1 | (Node _, Leaf _) -> -1 | (Node n1, Node n2) -> ASet.compare n1 n2 end and ASet : Set.S with type elt = A.t = Set.Make(A)
It can be given the following specification:
module rec A : sig type t = Leaf of string | Node of ASet.t val compare: t -> t -> int end and ASet : Set.S with type elt = A.t
关于module - OCaml 中的递归集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223952/