Home > Blockchain >  Ocaml function that from a matrix produces a modified matrix
Ocaml function that from a matrix produces a modified matrix

Time:05-10

So i have this little function:

let switch matrix =
  for i = 0 to Array.length matrix - 1 do
    for j = 0 to Array.length (Array.get matrix i) - 1 do
      if Array.get (Array.get matrix i) j = false then
        Array.set (Array.get matrix i) j true
    done
  done;;

Which basically flips all false values in a matrix to true value. This is not what im really going for, it's just to illustrate what ive tried so far.

The problem is is this function changes the values of the matrix instead of creating a matrix.

I actually need it to be a : bool array array -> bool array array =

What do i need to do in order to have a function that does that.

I've thought of pattern matching, so i've tried:

let switch matrix =
  for i = 0 to Array.length matrix - 1 do
    for j = 0 to Array.length (Array.get matrix i) - 1 do
      match Array.get (Array.get matrix i) j with true -> true | false -> true
    done
  done;;

But this function says: his expression should have type unit.

Sorry if this is a stupid question, i just started with OCaml

EDIT: So, i tried this:

let switch matrix =
  let newMatrix =
    Array.make_matrix (Array.length matrix)
      (Array.length (Array.get matrix 1))
      true
  in
  let switching matrixes = matrixes.(0).(0) <- false in
  switching newMatrix;
  newMatrix;;

but now, it's of type a array array -> bool array array = . But i need it to be bool array array -> bool array array. What can i do to move forward from this?

CodePudding user response:

Your solution after the edit is good. You just need to apply your first function (the one that modifies the matrix in place) to the new matrix you created.

CodePudding user response:

Starting from your first piece of code :

let switch matrix = for i = 0 to (Array.length matrix - 1) do 
    for j = 0 to ((Array.length (Array.get matrix i ))-1) do
             if Array.get (Array.get matrix i) j = false then Array.set (Array.get matrix i) j true
        done;
    done;

Formatting it properly and using the .() and .() <- operators for Array.get Array.set :

let switch matrix =
  for i = 0 to Array.length matrix - 1 do
    for j = 0 to Array.length matrix.(i) - 1 do
      if not matrix.(i).(j) then matrix.(i).(j) <- true
    done
  done

if expr = true is equivalent to if expr and if expr = false is equivalent to if not expr

Then creating a new matrix at the beginning of your code filled with true, modifying it according to matrix and returning it, we get :

let switch matrix =
  let n = Array.length matrix in 
  let p = Array.length (matrix.(0)) in
  let result = Array.make_matrix n p true in
  for i = 0 to n - 1 do
    for j = 0 to p - 1 do
      if matrix.(i).(j) then result.(i).(j) <- false
    done
  done;
  result
  • Related