如果我有一个定义规则的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).有人知道怎么做吗?
谢谢
发布于 2017-05-29 13:36:38
有一个ISO指令用于此目的(以及更多):initialization如果您有一个包含以下内容的文件,例如文件夹中的dog.pl
dog(john).
dog(ben).
:- initialization forall(dog(X), writeln(X)).当你查阅你得到的文件时
?- [dog].
john
ben
true.发布于 2017-05-29 06:06:55
请注意,仅仅断言dog(X).并不是将dog(X)作为查询调用,而是试图将其作为事实或规则进行断言,它将这样做并对单例变量发出警告。
以下是按照您描述的方式导致执行的方法(这适用于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)).这样做的目的是写出dog(X)查询的结果,然后通过false调用强制回溯到dog(X),它将找到下一个解决方案。这种情况会一直持续下去,直到不再有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
$发布于 2017-05-29 05:25:26
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 ?- https://stackoverflow.com/questions/44232140
复制相似问题