如何在swi-prolog中的prolog文件中运行prolog查询?

ome*_*ega 3 prolog

如果我有一个定义规则的prolog文件,并在windows中的prolog终端中打开它,它会加载事实.但是,它会显示?-我手动输入内容的提示.如何将代码添加到文件中,以便它实际评估这些特定语句,就像我键入它们一样?

这样的事情

dog.pl

dog(john).
dog(ben).

% execute this and output this right away when I open it in the console
dog(X).
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?

谢谢

Cap*_*liC 6

有一个ISO 指令就此目的(以及更多):初始化 如果你有一个文件,比如dog.pl在一个文件夹中,含有这个内容

dog(john).
dog(ben).

:- initialization forall(dog(X), writeln(X)).
Run Code Online (Sandbox Code Playgroud)

当你查阅你得到的文件

?- [dog].
john
ben
true.
Run Code Online (Sandbox Code Playgroud)


lur*_*ker 5

请注意,仅断言dog(X).不会dog(X)作为查询调用,而是尝试断言 is 作为事实或规则,它将执行此操作并警告有关单例变量的信息。

这是一种按照您所描述的方式执行的方法(这适用于 SWI Prolog,但不适用于 GNU Prolog):

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)).
Run Code Online (Sandbox Code Playgroud)

它的作用是写出查询的结果dog(X),然后通过调用强制回溯false,返回到dog(X)找到下一个解决方案。这种情况一直持续到没有更多的dog(X)解决方案最终失败为止。确保在 finally 失败时调用; true,以便在将所有成功查询写入 后整个表达式成功。truedog(X)dog(X)

?- [foo].
john
ben
true.
Run Code Online (Sandbox Code Playgroud)

您还可以将其封装在谓词中:

start_up :-
    forall(dog(X), (write(X), nl)).

% execute this and output this right away when I open it in the console
:- start_up.
Run Code Online (Sandbox Code Playgroud)

如果要运行查询然后退出,可以:- 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 Code Online (Sandbox Code Playgroud)


Kir*_*gin 3

狗.pl:

dog(john).
dog(ben).

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

然后:

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

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

3 ?- 
Run Code Online (Sandbox Code Playgroud)