Reputation: 37105
Here is my program:
reachable(X) :- start(X).
reachable(X) :- link(Y, X), reachable(Y).
start(london).
link(london, paris).
link(paris, london).
link(london, berlin).
link(paris, berlin).
link(berlin, paris).
Now if I query it, I get solutions:
?- reachable(X).
X = london ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
X = paris ;
...
Why does SWI-Prolog keep finding the same solutions?
How can I fix my program to return the set of solutions then halt?
Here's what I am looking for:
?- reachable(X).
X = paris ;
X = london ;
X = berlin ;
No
$ swipl --version
SWI-Prolog version 7.6.4 for amd64
Upvotes: 2
Views: 54
Reputation: 5519
The simplest solution is to use tabled execution:
% The next line is required for version 7.6.4, but is considered
% deprecated in the latest version of the SWI-Prolog compiler!
:- use_module(library(tabling)).
% The next line prepares the predicate reachable/1 for tabled execution!
:- table reachable/1.
reachable(X) :- start(X).
reachable(X) :- link(Y, X), reachable(Y).
start(london).
link(london, paris).
link(paris, london).
link(london, berlin).
link(paris, berlin).
link(berlin, paris).
Example:
?- reachable(X).
X = berlin ;
X = paris ;
X = london.
Upvotes: 1