I'm just start learning Prolog and facing a wired problem:
Suppose I have people waiting in two lines:
left(a,b).
left(c,i).
left(i,j).
right(k,j).
which represents lines like these:
line1:a,b line2: c,i,j,k.
What I want is to see if any of these people are in same line. What I've wrote is following rules:
nextto(X,Y):- left(X,Y);left(Y,X);right(X,Y);right(Y,X).
sameline(X,Y):- nextto(X,Y).
sameline(X,Y):- nextto(X,Z),sameline(Z,Y).
I convert "left/right
" into "nextto
" relationship between people.
And the code works fine when two peoples are actually in same lines. But if I try:
?- sameline(a,c)
Where "a" and "c" are not in same line. The program goes into infinite loop until runs out of local stack. I assume it keeps trying to find variable "Z" between "X" and "Y" and if not found, the program will just create another "Z" to keep searching. I've seen the typical ancestor example using recursive call:
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z),ancestor(Z,Y).
which makes sense. But how is my code different from the ancestor example? Apparently nextto(a,j)
will return false, but why the loop won't stop?
It's my second day of learning Prolog, so advanced use of Prolog might not help :(.
Thanks.
sameline(c,X)
, e.g what values of X makes it succeed?? – codersameline(c,i) sameline(c,j) sameline(c,k)
will all return true since they are in same line. – Monkeyright(k,j)
?? Then we would havec ->i -> j and k->j
would these be two lines or k is considered in the line c,i,j?? – coderright(j,k)
? This will cause error to the program. But the question here I don't need to consider this situation. Assume all the conditions are well ordered. – Monkeyright(j,k)
,Assume all the conditions are well ordered
you mean that the lines will be clear (e.g we will not have examples like c ->i -> j and k->j) ?? – coder