How to keep inner mutable data synchronized

I’ve come across a case where I need to keep 2 data structures, say A and B, synchronized. The problem is that elements of A can be obtained by external code. Since these elements of A must be mutable for performance reasons, there’s no way for me to make sure the user doesn’t directly modify elements of A after accessing them. In C++, I would make a A_elem const get() method that would prevent modification of A elements by specific methods. Since we don’t track mutability by function call in OCaml, I don’t have that option. Is there another method I could use to get similar results?

1 Like

It is possible to hide mutability using a private annotation.

module M : sig
  type t = private { mutable x : int }
  val mk : int -> t
  val get : t -> int
  val incr : t -> unit
end = struct
  type t = { mutable x : int }
  let mk x = {x}
  let get {x} = x
  let incr t = (t.x <- t.x + 1)
end;;

let test = M.mk 0;;
val test : M.t = {M.x = 0}

# M.incr test;;
- : unit = ()

# M.get test;;
- : int = 1

# test.M.x <- 3;;
Error: Cannot assign field M.x of the private type M.t
4 Likes