用和键入声明

时间:2013-01-29 23:21:10

标签: functional-programming ocaml

类型声明的好处是什么:

type xxx
and yyy

type xxx
type yyy

给它一个依赖于另一个的语义?

我使用OcamlWin 4.0,代码来自C:\OCaml\lib\hashtbl.ml

  type ('a, 'b) t =
  { mutable size: int;                        (* number of entries *)
    mutable data: ('a, 'b) bucketlist array;  (* the buckets *)
    mutable seed: int;                        (* for randomization *)
    initial_size: int;                        (* initial array size *)
  }

and ('a, 'b) bucketlist =
    Empty
  | Cons of 'a * 'b * ('a, 'b) bucketlist

它编译。当我将and更改为type

type ('a, 'b) t =
  { mutable size: int;                        (* number of entries *)
    mutable data: ('a, 'b) bucketlist array;  (* the buckets *)
    mutable seed: int;                        (* for randomization *)
    initial_size: int;                        (* initial array size *)
  }

type ('a, 'b) bucketlist =
    Empty
  | Cons of 'a * 'b * ('a, 'b) bucketlist

也可以编译。

2 个答案:

答案 0 :(得分:3)

定义相互递归声明时经常使用and关键字

给出你的例子

type ('a, 'b) t =
    { mutable size: int;                        (* number of entries *)
      mutable data: ('a, 'b) bucketlist array;  (* the buckets *)
      mutable seed: int;                        (* for randomization *)
      initial_size: int;                        (* initial array size *)
    }

type ('a, 'b) bucketlist =
    Empty
  | Cons of 'a * 'b * ('a, 'b) bucketlist

会在第3行给出Error: Unbound type constructor bucketlist,字符为20-39。但是,用a更改第二种类型并将删除错误。

type ('a, 'b) t =
    { mutable size: int;                        (* number of entries *)
      mutable data: ('a, 'b) bucketlist array;  (* the buckets *)
      mutable seed: int;                        (* for randomization *)
      initial_size: int;                        (* initial array size *)
    }

and ('a, 'b) bucketlist =
    Empty
  | Cons of 'a * 'b * ('a, 'b) bucketlist

我无法想出为什么它会在两种情况下为你编译的原因,但是如果你使用解释器并且忘记关闭它,那么它将在其环境中具有旧的绑定。
也就是说,如果您首先使用and关键字对代码进行评估,那么您可以继续重新评估代码,而不必在环境中定义bucketlist

答案 1 :(得分:2)

表达相互递归定义需要and关键字。例如,

type t = A | B of u
and  u = C | D of t
如果您要将and替换为type

将无法再编译。在您的示例中,它的使用是多余的。