Gustavo Gomes
Gustavo Gomes

Reputation: 327

Matching a char in a matrix on Ocaml

I am making a game solver and while using a matrix in OCaml, I need to check whenever it's complete, with A's or V's, to do so I attempeted to see if there is a '.' in at least one of the cells because that symbolizes an empty cell. Here goes the code:

let is_solved m n =
  for i=0 to n do
    for j=0 to n do
      if(m.(i).(j)='.') then false
    done
  done;;

So my is_solved function has to return false when it finds a '.' at any position or true if it doesn't. But OCaml is giving me a:

Error: The variant type unit has no constructor false

I am new to OCaml but can someone tell me what I need to fix or even why is it giving me that error message?

Upvotes: 0

Views: 140

Answers (2)

ivg
ivg

Reputation: 35280

You can write this function in a recursive way as Jeffrey has suggested, just to give you a starting kick, I will provide a general template letting you to fill the gaps:

let todo = failwith

(* [is_solved field m n] true if exists '.' in the [field], where
   [field] is a matrix of size [m] x [n] *)
let is_solved field m n = 
  let rec outer = function 
    | 0 -> todo "outer loop ends" 
    | m -> inner m n 
  and inner m = function
    | 0 -> todo "inner loop ends"
    | n -> todo "inner loop workload" in
  outer m

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

First, note that the value of any OCaml construct of the form for ... done is (), the single value of type unit. You can't give a value to the loop as you seem to be trying to do.

Your immediate problem is that when you use if without else in OCaml, the value of the expression has to be of type unit. This is necessary because the type has to be the same in both cases. However, it's not really worth fixing this due to the above problem.

If you want to use for loops to solve your problem, you'll need to use an imperative approach. That is, you'll need to keep a mutable value to hold what you want to return at the end.

(Since you're new to OCaml it might be useful to try coding this function in a more functional style just to see how it looks.)

Upvotes: 1

Related Questions