Question

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
Was it helpful?

Solution

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).

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top