在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中——我正在考虑的编码会非常简单地使用依赖类型索引),但它肯定可以更直接地说得更清楚。