找到一组解决方案并在 SWI-Prolog 中终止?
Find set of solutions and terminate in SWI-Prolog?
这是我的程序:
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).
现在如果我查询它,我得到解决方案:
?- 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 ;
...
为什么 SWI-Prolog 一直在寻找相同的解决方案?
如何修复我的程序以return解决方案集然后停止?
这是我要找的东西:
?- reachable(X).
X = paris ;
X = london ;
X = berlin ;
No
$ swipl --version
SWI-Prolog version 7.6.4 for amd64
最简单的解决方案是使用表执行:
% 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).
示例:
?- reachable(X).
X = berlin ;
X = paris ;
X = london.
这是我的程序:
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).
现在如果我查询它,我得到解决方案:
?- 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 ;
...
为什么 SWI-Prolog 一直在寻找相同的解决方案?
如何修复我的程序以return解决方案集然后停止?
这是我要找的东西:
?- reachable(X).
X = paris ;
X = london ;
X = berlin ;
No
$ swipl --version
SWI-Prolog version 7.6.4 for amd64
最简单的解决方案是使用表执行:
% 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).
示例:
?- reachable(X).
X = berlin ;
X = paris ;
X = london.