如何定义相互组成的类型

How to define to type that comprise each other

我正在使用 ocaml 为 bean 构建一个简单的编译器。在 bean 中,每个类型定义都包含

  1. 关键字 'typedef',
  2. 类型说明,

  3. 一个标识符。

以下任一类型规范:

1.the 关键字 'bool' 或 'int'

2.a 逗号分隔的字段定义列表,由 { 和 }

包围

3.an 标识符

我想像这样定义两个类型:

type field_def = (ident * typespec)

type typespec =
  | Bool 
  | Int
  | Tident of ident
  | Tfield_def of field_def list

type typedef = (ident * typespec)

我在field_def的定义中使用了type,但是在下一个定义中定义了,所以总会出现type unbound的错误。我该如何解决?

当你想创建相互依赖的类型时,你必须使用and:

type a = A | OfB of b
and b = B | OfA of a

和定义互递归函数时一样:

let rec is_even n = n = 0 || is_odd (n - 1)
and is_odd n = n <> 0 && is_even (n - 1)