代码之家  ›  专栏  ›  技术社区  ›  Jack

OCaml中的递归集

  •  5
  • Jack  · 技术社区  · 15 年前

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

    问题是 值集 value 价值 可以是一个 值集 所以我在编译的时候遇到了麻烦。

    types.ml (有自己的接口) types.mli 但是没有 模块decl,因为我也不确定这是可能的)。

    这个问题能以某种方式解决吗?

    1 回复  |  直到 15 年前
        1
  •  7
  •   Xilexio    7 年前

    可以使用递归模块。 Language manual 使用与递归集类型完全相同的示例来说明此语言功能。以下是相关摘录。

    递归模块定义的典型示例如下:

    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)
    

    其规格如下:

    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