types - OCaml 可变变体类型

标签 types ocaml immutability mutable mutability

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/

相关文章:

haskell - Haskell的两级类型层次结构

ocaml - 初始化一个 int64 变量

scala - 为什么 Scala 的 toSeq 将不可变的 Set 转换为可变的 ArrayBuffer?

java - 为什么内在锁对象不需要特殊处理(static、final、volatile)?

java - 启用 VisibilityModifier checkstyle 模块时如何允许不可变类?

haskell - 绑定(bind)来自哪里?

php - 在 PHP 中处理货币值的最佳实践?

parsing - 一个好的 ocaml 解析器?

TypeScript:导入和导出 "at the same time"

ocaml - 从 C 头文件生成 Ocaml 绑定(bind) stub