Reputation: 1119
I'm new to OCaml and i'm trying to understand the concept of mutable record field
.
I'd like to create an array of records and that record contains a boolean mutable field. So i did something like:
type t = {i: int; mutable b: bool};;
I want to be able to change the value of the 'b' field of the record, so i put it mutable
let m = Array.make 10 ({i = 5; b = false});;
Here i try to set the b field of the record located at the first index of my array :
(Array.get m 0).b <- true;;
The problem is want i do it, it will set 'b' field of all the records of the array, and this is not what i want.
Does the mutable fields of a same record share the same memory emplacement? How can i do to change the value of the 'b' field of a specific record?
Upvotes: 1
Views: 643
Reputation: 373
As the documentation states, Array.make
creates an array whose elements are all physically equal. That's not a problem if these elements are immutable, but as you saw, you have to take that into account if they are mutable.
What you can do is use Array.init
, to create a different object for every cell of your array:
let m = Array.init 10 (fun _ -> {i = 5; b = false});;
Upvotes: 7