Voss
Voss

Reputation: 3

Assign variable to array element where variable and array can be modified independently in ocaml

Here is the problem I can't get around, I'm working in ocaml to copy the elements of an array to a new array. I want to be able to modify these arrays independently from each other, but no matter what I try, a change to one array is reflected in the other array as well. Here is a simplified example:

type sampleType = { a : int; b : int array };;
let x = {a = 5; b = [|1, 2, 3|] };;
let y = x.b;;
Array.set y 1 6;;

After running these commands I want:

y - : int array = [|1; 6; 3|]
x - : sampleType = {a = 5; b = [|1; 2; 3|]}

Instead x is being changed along with y, and

x - : sampleType = {a = 5; b = [|1; 6; 3|]}

Any solutions to this problem?

Upvotes: 0

Views: 119

Answers (2)

Voss
Voss

Reputation: 3

I was specifically using 3d arrays, realized I had to apply Array.copy at the lowest level of the 3d array, rather than at the top level.

let arr = Array.init 3 (fun _ -> Array.init 3 (fun _ -> (Array.init 3 (fun _ -> {faces = [|0;1;2;3;4|]}))));;
let drr = Array.init 3 (fun i -> Array.init 3 (fun j -> Array.copy arr.(i).(j)));;

This gave me the result I needed.

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

As you see from your experiments, this code:

let y = x.b

makes y refer to the very same array as x.b. It doesn't create an independent array. To create an independent array, you need to copy:

let y = Array.copy x.b

Upvotes: 1

Related Questions