 # Trouble with updating a 2d array with ReasonML (compiling to JS)

#1

Hello everyone!

Sorry to bother you but I am having trouble updating a 2d array, and I think I have not screwed up anything obvious.

Here is the sketch (copied from @thangngoc89): https://sketch.sh/s/HqfcmU5IBWiSNWjClEZrVB/

I don’t know what’s going on, but I am quite sure it is a mistake on my part, just not sure what. If someone could help I would really appreciate it.

Thank you.

#2

Hey! The issue is that you’re initializing an array containing 3x a reference to the same array.
So effectively `matrix[r] === matrix[r] === matrix[r]` (try running it inside the sketch.sh file).

You can solve this using `Array.make_matrix` #3

Thank you @bsansouci!

Also, it doesn’t seem like make_matrix supports only 2d arrays right?

#4

I think `Array.make_matrix` only returns a 2D array. You can’t make it return an `array(array(array('a)))` for example.

#5

Wait, so how do you create 3d/higher multidimensional arrays in ReasonML/BuckleScript/OCaml?

#6

You can do it with a recursive function and a loop:

``````let make_3d_matrix = (dimx, dimy, dimz) => {
let matrix = ref(Array.make(dimx, [||]));
for (i in 0 to dimx - 1) {
matrix.contents[i] = Array.make_matrix(dimy, dimz, 0);
};
matrix.contents;
};
``````

And for higher dimensions you can nest them. I’m not sure you can make a function that returns a matrix of arbitrary nested arrays because the return type of the function cannot be different from one call to another, so any branch of the function returns `array(int)` and another branch returns `array(array(int))` then the compiler will say “idk what to do here bro”. So you’d need to “unify” the different things that can be returned using a variant, in which case your simple matrix becomes a `type t = MatrixOfLengthN | BaseArray(array(int))` kinda thing , and then you’re returning something of type `t` and of value `MatrixOfLengthN(MatrixOfLengthN(BaseArray([||])))` for a 3d matrix etc… Which is probably not what you’d like. I’d recommend finding ways to avoid needing arbitrary nested arrays.