Xonram
Xonram

Reputation: 1

Running in a problem with matrices in ocaml

So I have just recently started programming in ocaml for my university (it is required here). I have to write a function unit->(int*int) Array Array Array which creates a 16 by 16 matrix, in which entries are Arrays which take in 4 tuples.

I was explicitly told to not write this function recursivly, so I made this :

let matrice_deplacements () = 
  let u = Array.make 16 (Array.make 16 [||]) in
  for k=0 to 15 do
    for p=0 to 15 do
      u.(k).(p)<-deplacement_grille (k,p)
    done;
  done;
u;;

And I know for sure that the function deplacement_grille (excuse the french) works perfectly, and gives me exactly what I want ( which is the right (int*int) Array, for the good k and p)

I have absolutely no clue where the problem lies, because each time I've run this code(I've tried with 2*2 and 3*3 matrices, and it doesn't work), ocaml returns a matrix, where all the lines are the same(they are actually what was supposed to be the last line).

Any help is appreciated. I actually wonder if this comes down to the way ocaml stores Array, it may like python, where they have the same adress.

Upvotes: 0

Views: 141

Answers (1)

CraigFe
CraigFe

Reputation: 66

I suggest consulting the documentation of Array.make, which explains that arrays constructed in this manner have elements that are physically equal. As such, your initial line builds 2 distinct arrays, not the 17 that you expect. (This has to be the case, since the inner constructor application (Array.make 16 [||]) is evaluated to a single array before passing it to the constructor of the outer array.)

You probably want Array.init instead, which constructs a fresh element for each index. There is also Array.make_matrix, which is like Array.make in that the matrix elements are initially physically equal.

Upvotes: 3

Related Questions