module - OCaml 中的递归集

标签 module ocaml recursion

我怎样才能定义一个 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)

问题是 ValueSetvalue因为它是 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/

相关文章:

python - 在 Python 2.7 中如何将文本 (.txt) 文件作为 .py 文件读取?

multicore - 如何在 Ocaml 中使用多核进行蒙特卡罗模拟?

javascript - 迭代嵌套的数字键控 json 对象

c# - 仁慈SSH.NET : Is it possible to create a folder containing a subfolder that does not exist

python - 递归传递关键字

python - 如何从 URL 导入 Python 模块?

c++ - 尝试模拟 SystemC 文件时出现 "multiple definition of"消息

python - 是否可以发送 'OptionParser' 对象作为输入参数来运行导入的 python 模块的 main ?

python - 在 python 中集成 OCaml - 如何从 python 中保持 ocaml session ?

ocaml - OCaml 或 Core 中是否有通用的调试打印?