Reputation: 2001
I've been tampering with this code for the past couple hours.
What the function should do, is return a list of the next reachable states from the current state (X/Y). Obs
is a list of unreachable states, N
is the number of rows, M
is the number of columns.
So a typical return answer for successors(2/2, X)
would be: X = [ (1, [3/2]), (1, [1/2]), (1, [2/3])| (1, [2/1])].
The code I have so far works if all the predicates are true, and it returns the correct output. However, if any of the successor helper predicates are wrong, then it fails.
succesors(X/Y, Succs):-
loadMazeInfo(maze1), %loading the maze info
maze(_, M, N, Obs, _, _), %obtaining the S and G states.
successorsRight(X/Y, Succs, Obs, M, N).
successorsRight(X/Y, [(1, [S1/Y])|T], Obs, M, N):-
successorsLeft(X/Y, T, Obs, _, N), S1 is X + 1, M >= S1, not(member(S1/Y, Obs)).
successorsLeft(X/Y, [(1, [S1/Y])|T], Obs, _, N):-
successorsUp(X/Y, T, Obs, _, N), S1 is X - 1, S1 >= 1, not(member(S1/Y, Obs)).
successorsUp(X/Y, [(1, [X/S2])|T], Obs, _, N):-
successorsDown(X/Y, T, Obs, _, _), S2 is Y + 1, N >= S2, not(member(X/S2, Obs)).
successorsDown(X/Y, (1, [X/S2]), Obs, _, _):-
S2 is Y - 1, S2 >= 1, not(member(X/S2, Obs)).
I am wondering if there is a way to tell prolog to skip the predicate if it's false, and go to the next one. Or is this unachievable and I'm tackling the problem completely wrong? I don't understand cuts properly, but I wouldn't think they'd be useful for me in this case, or are they?
Upvotes: 1
Views: 182
Reputation: 60014
I think you're 'overspecifying' the logic. You should simplify your program, factorizing repeated code, and let Prolog search available steps. Then findall/3 will help you to build the results' list
succesors(X/Y, Succs):-
loadMazeInfo(maze1), %loading the maze info
maze(_, M, N, Obs, _, _), %obtaining the S and G states.
findall((1,SX/SY), (successor(X, Y, SX, SY, M, N), not(member(SX/SY, Obs))), Succs).
successor(X, Y, S1, Y, M, _):-
S1 is X + 1, M >= S1.
successor(X, Y, S1, Y, _, _):-
S1 is X - 1, S1 >= 1.
...
Upvotes: 3