matrixocamlsetvalue

Copying a matrix into another matrix ocaml


I am trying to copy a the values of the first matrix to the second element by element. I don't understand why "<-" doesn't work for me when I want to set a new value. Here's the code:

let y=[|[|"true";"true";"false";"false"|];
        [|"true";"false";"true";"false"|];
        [|"false";"false";"true";"true"|];
        [|"false";"true";"false";"true"|]|]
;;

let fill_array = 
  let l=Array.length x in
  for i=0 to l-1 do
    for j=0 to l-1 do
      x.(i).(j)<-(y(i).(j))
    done;
  done;
  x;;

I get the following-Error: This expression has type string array array This is not a function; it cannot be applied. Ideally this would be a bool array but I wanted to try string first.


Solution

  • You are missing a dot. In

    x.(i).(j)<- y(i).(j)
    

    y(i) is a function application whereas you wanted y.(i)

    x.(i).(j)<- y.(i).(j)
    

    Note that for an element-by-element copy, another option would be to use higher-order functions rather than low-level loops:

    let copy x y =
      Array.iteri (fun i xi ->
        Array.iteri (fun j x -> y.(i).(j) <- x) xi
      ) x