Reputation: 113
I'm trying to write a function in OCaml that, given a coordinate in a matrix containing entries "u", "d", "l", "r", and "x", returns true if following the 'directions' from that coordinate ends at "x", or false otherwise.
My strategy is to check if I've visited the current cell before (if so, return false), by passing a matrix t of bools through, updating the value of the current cell to true.
My current attempt is below (n is the sample matrix I'm trying to navigate):
let n = [| [|"u"; "d"; "l"; "l"; "r"|];
[|"r"; "d"; "r"; "l"; "l"|];
[|"u"; "r"; "d"; "d"; "l"|];
[|"u"; "l"; "l"; "d"; "u"|];
[|"r"; "x"; "l"; "l"; "d"|];
[|"r"; "d"; "u"; "d"; "l"|]|];;
let xMax = (Array.length n);;
let yMax = (Array.length n.(0));;
let t = Array.make_matrix xMax yMax false;;
let rec f m x y t =
if x < 0 || y < 0 || x >= (Array.length m) || y >= (Array.length m.(0)) || t.(x).(y) = true
then false
else (
if m.(x).(y) = "x" then true
else (
t.(x).(y) <- true
if m.(x).(y) = "l" then f m x (y-1) t
else if m.(x).(y) = "r" then f m x (y+1) t
else if m.(x).(y) = "u" then f m (x-1) y t
else if m.(x).(y) = "d" then f m (x+1) y t
else false
)
);;
Can anyone help with how to fix this? It's the line
t.(x).(y) <- true
that isn't working (commenting it out makes the function run, but doesn't update the matrix t).
Thanks in advance!
Upvotes: 1
Views: 343
Reputation: 35280
You missed a semicolon after the t.(x).(y) <- true
expression. Without the semicolon, you program is parsed by the compiler as:
t.(x).(y) <- (true if m.(x).(y) = "l" then f m x (y-1) t ...)
Upvotes: 2