2
votes

So, im working with this following code:

test:- p(X,Y), r(Y), s(X), write(X), nl, fail.
test.

test2(X,Y):- p(X,Y), r(Y).

p(3,4).
p(6,9).
p(7,8).

r(X):- s(X), t(X).

s(7).
s(6):-!.
s(8).

t(9).
t(8).
t(5):-!.
t(4).

s(X) returns X=7;X=6.

t(X) returns X=9;X=8;X=5.

Obviously, r(X) returns false.

My question is, how the hell then test2(X,Y) returns X=7,Y=8?

1

1 Answers

3
votes

r(X) will fail... but r(8) will not! This is because if you use r(X), the system searches until it encounters the ! operator, then stops searching. But if you ask it for r(8) directly, it will never encounter the ! operator in the first place.

So when the system unifies p(X,Y) with p(7,8), the next step is to try r(8), which leads to s(8), t(8). Both of these succeed, because they look for s(8) and t(8), rather than s(X) and t(X). So they don't encounter the ! operator. The result is that r(8) evaluates to true, eventually leading to X=7, Y=8.

Guess it illustrates how careful one must be when using !.