문제

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
도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top