注意,只是斷言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