Reputation: 646
Here is my simple Prolog program:
friend(X,Y):-
knows(X,Y).
friend(X,Z):-
friend(X,Y),
friend(Y,Z).
knows(brian,tom).
knows(tom,peter).
If I type the following query
friend(brian,peter).
Prolog will give the following output:
?- friend(brian,peter).
true
If a further type a semicolon, Prolog will say:
ERROR: Out of local stack
What am I doing wrong here?
Upvotes: 3
Views: 13496
Reputation: 10102
The understand the source of non-termination in your program it suffices to look at the following failure-slice:
friend(X,Y):- false,knows(X,Y). friend(X,Z):- friend(X,Y), false,friend(Y,Z).knows(brian,tom) :- false.knows(tom,peter) :- false.
It is because of friend(X, Z) :- friend(X, Y), ...
that your program will not terminate. It will produce answers, here and there, but ultimately it will loop. For more, see failure-slice.
Upvotes: 1
Reputation: 18663
The error is in the second clause. It should be instead:
friend(X,Z):-
knows(X,Y),
friend(Y,Z).
Otherwise, when you ask Prolog for more solutions, you end up having the friend/2
predicate recursively calling itself without first establishing a knows/2
intermediate relation. You can learn more about the bug in your program by tracing the calls to the friend/2
predicate. Try:
?- trace, friend(brian,peter).
Upvotes: 5