Reputation: 14295
Caml Light manual mentions mutable variant types on page 37:
type foo = A of mutable int
| B of mutable int * int
But this extension doesn't seem to be a part of OCaml, or is it? Am I right that the only way to define a mutable variant type in OCaml is to use mutable records or arrays?
(* 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
Edit: Thanks @gasche suggesting using refs, which are a shortcut for mutable record:
type foo = A of int ref
| B of int ref * int ref
Upvotes: 2
Views: 1043
Reputation: 92
You could use refs as a shorthand.
Check 2.2 Mutable storage and side effects from http://caml.inria.fr/pub/docs/u3-ocaml/ocaml-core.html
Upvotes: 2
Reputation: 31469
Indeed, mutable variants were dropped in the transition between Caml Light and OCaml, in part because the syntax to manipulate them was so awkward (pattern-matching on a mutable field would make the pattern identifier a lvalue, yumm...).
The current ways to express mutability are through mutable record fields (which have a proper field mutation syntax), or references int ref
(which are defined as one-field mutable records).
Upvotes: 3