Caml Light manual在第 37 页提到可变变体类型:
type foo = A of mutable int
| B of mutable int * int
但是这个扩展似乎不是 OCaml 的一部分,是吗? 在 OCaml 中定义可变变体类型的唯一方法是使用可变记录或数组,我说得对吗?
(* with records *)
type a = {mutable a: int}
and b = {mutable b1: int; mutable b2: int}
and foo = A of a
| B of b
(* with arrays *)
type foo = A of int array
| B of int array
编辑:感谢@gasche 建议使用 refs,这是可变记录的快捷方式:
type foo = A of int ref
| B of int ref * int ref
最佳答案
事实上,可变变体在 Caml Light 和 OCaml 之间的转换过程中被丢弃了,部分原因是操作它们的语法非常笨拙(可变字段上的模式匹配会使模式标识符成为左值,yumm ...) .
当前表达可变性的方法是通过可变记录字段(具有适当的字段突变语法)或引用 int ref
(定义为单字段可变记录)。
关于types - OCaml 可变变体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365318/