Reputation: 21
I need to implement a board game, using Prolog. The game consists of a board(10x5), two characters(a cop and a thief) and some objects scattered over the board. The objective is to find wheter there is a path from the cop to the thief, provided that the thief cannot move. I tried to define the cop's movement as follows:
/*Defining the movement along the x-axis*/
cop(0). /*Initial position.*/
cop(W) :- cop(X), W is X+1, W < 10.
In doing so, I encountered two major problems: the solution above enters an infinite loop, when presented with the query "?- cop(X).", and prints the following
and when I try to make the cop move left, with : cop(W) :- cop(X), W is X+1, W > 0.
, i get the same error message. How can I do it?
Upvotes: 2
Views: 356
Reputation: 476544
The essential problem here is that you define a left-recursive function:
cop(W) :-
cop(X),
...
this means that Prolog can keep calling cop/1
, since if you call cop(W)
, you call cop(X)
, and that cop(X)
, will again result in a call to cop(Y)
, etc. You only set bounds at the end, and thus there is no "guard" that protects against the recursion. Even if the "filtering" at the end lets all the suggested solutions fail, then nothing will prevent Prolog from retrying this, but with one recursive call extra. So after a while the filtering will discard all proposed solutions, but Prolog will keep searching for a valid solution.
A trick is thus here to limit the recursion, we can for example use the clpfd
library to "limit" the bound of the W
variable, and eventually obtain an empty domain, like:
:- use_module(library(clpfd)).
cop(0).
cop(W) :- W #> 0, W #=< 10, W #= X+1, cop(X).
that being said, I am not confident that the above way to handle this puzzle. It looks like you will need to use linear temporal logic (LTL), or branching temporal logic (BTL) here.
Upvotes: 2