OCaml 中的相互递归类型

Mutually recursive types in OCaml

在 Haskell 中,您可以执行以下操作:

Prelude> data Foo = Foo Bar; data Bar = Bar Foo

如何在 OCaml 中做同样的事情?我试过了:

                    ___
# type foo = Foo of bar;; type bar = Bar of foo;;
Error: Unbound type constructor bar

是否可以在 OCaml 中定义相互递归的数据类型?如果不是那为什么?

比较数据定义与 let 表达式:相互递归的数据类型对应于使用 let rec(或者更恰当的是 type rec,因为需要更好的短语)。能够定义相互递归的数据类型有什么好处?我的 foobar 示例很简单。您能想到相互递归数据类型的任何重要用途吗?

使用and

type foo = Foo of bar
 and bar = Bar of foo

ivg 回答了你的问题,但这里有一个非平凡的相互递归类型。

module Stream = struct

  type 'a t    = unit -> 'a node
   and 'a node = Nil
               | Cons of 'a * 'a t 

end

这是真正的懒惰流。也就是说,您可以在没有相互递归类型的情况下构建它

type 'a t = Stream of (unit -> ('a * 'a t) option)

我的想法是,如果你愿意,你总是可以将一系列相互递归的类型缩减为一个类型(尽管可能不是在 OCaml 中——我正在考虑的编码将对依赖类型进行非平凡的使用indices),但是直接肯定可以更清楚