注意,只是断言dog(X).
不叫dog(X)
作为查询,而是试图断言是一个事实或规则,它会做和警告一个单身变量。
这里有一个方法来导致执行你所描述的方式(这适用于SWI Prolog的,但不是GNU序言):
foo.pl
内容:
dog(john).
dog(ben).
% execute this and output this right away when I open it in the console
% This will write each successful query for dog(X)
:- forall(dog(X), (write(X), nl)).
这样做是写出来的查询的结果为dog(X)
,然后通过false
调用强制回溯,返回到dog(X)
,这会找到下一个解决方案。这一直持续到最终失败的解决方案不再存在为止。 ; true
确保当dog(X)
最终失败时调用true
,以便在将所有成功的查询写出到dog(X)
之后,整个表达式成功。
?- [foo].
john
ben
true.
你也可以将其封装在一个断言:
start_up :-
forall(dog(X), (write(X), nl)).
% execute this and output this right away when I open it in the console
:- start_up.
如果你想运行查询,然后退出,你可以从文件中删除:- start_up.
和命令行运行它:
$ swipl -l foo.pl -t start_up
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.2.3)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
john
ben
% halt
$
把'run'前缀没有得到任何输出,但不要把它只输出第一个结果。 – omega