Jac*_*ack 5 recursion ocaml module
如何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*)
Run Code Online (Sandbox Code Playgroud)
另外,我ValueSet在同一个文件中声明了一个具体的模块:
module ValueSet = Set.Make(struct type t = value let compare = Pervasives.compare end)
Run Code Online (Sandbox Code Playgroud)
问题是ValueSet有value,因为它是ELT类型,但value可以是一个ValueSet,所以我得到的麻烦,同时试图对其进行编译.
所有这些声明都只包含在一个名为的文件中types.ml(它有自己的接口types.mli但没有任何ValueSet模块decl,因为我不确定它是否可行).
这个问题能以某种方式解决吗?
您可以使用递归模块.语言手册使用与递归集类型完全相同的示例来说明此语言功能.以下是相关摘录.
递归模块定义的典型示例是:
Run Code Online (Sandbox Code Playgroud)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)它可以给出以下规范:
Run Code Online (Sandbox Code Playgroud)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