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?
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).