2017-05-28 115 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.