简体   繁体   English

如何在prolog中定义谓词

[英]How to define a predicate in prolog

I am new to Prolog and I have so far learned how to define a predicate in a file and the run the interpreter to use it. 我是Prolog的新手,到目前为止我已经学会了如何在文件中定义谓词并运行解释器来使用它。 But I would like to know if there is a way to define the predicate at the ?- prompt so that I don't have to switch back and forth. 但我想知道是否有一种方法可以在? - 提示符下定义谓词,这样我就不必来回切换。

the way I am doing it now is like this 我现在这样做的方式是这样的

file defs.pl: 文件defs.pl:

adjacent(1,2).
adjacent(1,3).

in the prolog interpreter: 在prolog翻译:

?- consult('defs.pl').
% defs.pl compiled 0.00 sec, 122 bytes
true.
?- adjacent(1,2).
true.

EDIT maybe I meant how to define 'facts' I'm not sure. 编辑也许我的意思是如何定义'事实'我不确定。

You can use the assert/1 predicate: 您可以使用assert/1谓词:

?- assert(adjacent(1,4)).
true

EDIT: By the way, this will not work if you try to combine it with predicates defined in a file. 编辑:顺便说一句,如果您尝试将其与文件中定义的谓词组合,这将不起作用。 So either define all adjacent/2 predicates in your file, are define them all with assert in the command line. 因此,要么在文件中定义所有相邻的/ 2谓词,请在命令行中使用assert定义它们。

If you do want to define some of the predicates in the file, and others with assert, then declare in your file that the predicate is dynamic: 如果您确实想要在文件中定义一些谓词,而其他谓词定义为assert,则在文件中声明谓词是动态的:

% file contents
:- dynamic(adjacent/2).
adjacent(1,2).
adjacent(1,3).

You can do 你可以做

?- consult(user).

or 要么

?- [user].

and enter the clauses after that, then terminate the input with the end of file character (Ctrl-D in Linux, could be Ctrl-Z in MS-Windows). 然后输入子句,然后用文件末尾字符终止输入(在Linux中为Ctrl-D,在MS-Windows中可以是Ctrl-Z)。 This is equivalent to reading a file, see the documentation of consult/1 . 这相当于读取文件,请参阅consult / 1的文档

assert/1 and retract/1 are intended for predicates that are changed dynamically by the code (ie for storing global data), not for normal programming. assert / 1和retract / 1用于由代码动态更改的谓词(即用于存储全局数据),而不是用于正常编程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM