2017-05-28 164 views
1

如果我有一個定義規則的prolog文件,並在窗口的prolog終端中打開它,它會加載事實。但是,它顯示?-提示我手動鍵入內容。我怎樣才能將代碼添加到文件中,以便它實際上評估那些特定的語句,就像我輸入它們一樣?如何在swi-prolog中的prolog文件內運行prolog查詢?

像這樣

dog.pl

dog(john). 
dog(ben). 

% execute this and output this right away when I open it in the console 
dog(X). 

有誰知道如何做到這一點?

感謝

回答

0

dog.pl:

dog(john). 
dog(ben). 

run :- dog(X), write(X). 
% OR: 
% :- dog(X), write(X). 
% To print only the first option automatically after consulting. 

然後:

$ swipl 
1 ?- [dog]. 
% dog compiled 0.00 sec, 4 clauses 
true. 

2 ?- run. 
john 
true ; # ';' is pressed by the user 
ben 
true. 

3 ?- 
+0

把'run'前綴沒有得到任何輸出,但不要把它只輸出第一個結果。 – omega

2

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

有一個ISO 指令這樣的目的(及以上):initialization 如果你有一個文件,dog.pl說一個文件夾中,與此內容

dog(john). 
dog(ben). 

:- initialization forall(dog(X), writeln(X)). 

當您諮詢文件你

?- [dog]. 
john 
ben 
true.