'mutable' usages

  • Question 1: in camllight we can have
type t = A of mutable t ;;

How to get an equivalent type in OCaml?

  • Question 2: in F# we have
let a = ref 10
a := !a + 1

and also

let mutable a = 10 
a <- a + 1

Could this syntax be useful in OCaml?

(the <- operator already exists).

type t = A of {mutable t: t}


1 Like

Re: question 1, I am unsure how this could ever be useful. The point of singleton sum types is usually to get a newtype without the hassle of defining a module. So here you appear to want a mutable new type. You can do this with:

type new_int = { mutable x : int }

which will be easier to use than your type as you can use the projection syntax.

I could see this being useful if records were structurally typed (ie if isomorphic records were considered the same type) but in OCaml they are not.

Re: question 2. I am also unsure how this can be useful. What’s the difference between the two in F#? If the difference is that the second one is not boxed, I believe OCaml actually optimizes the first one in such a way when it can.

For question 2, OCaml doc on Impertive Features says in OCaml you can either

  1. declared mutable in the definition of the record type
    type mutable_point = { mutable x : float; mutable y : float; }

  2. the standard library provides references, which are mutable indirection cells. however, references are implemented as a single-field mutable record
    type 'a ref = { mutable contents : 'a; }

Your second snippet won’t appear in OCaml.