且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog - 通过推导减少知识库

更新时间:2022-12-01 09:21:19

首先,您需要选择一个不同的谓词名称,因为 is/2 是计算算术表达式的内置函数,例如

Firstly, you need to pick a different predicate name, since is/2 is a built-in to evaluate arithmetic expressions, e.g.

?- X is 3+2.
X = 5.

如果您尝试查阅源文件,您的代码会导致以下错误:

Your code leads to the following error if you try to consult the sourcefile:

?- [myfile].
ERROR: /home/someuser/code/myfile.pl:1:
        dynamic/1: No permission to modify static procedure `(is)/2'

让我们将其重命名为 is_a/2.然后你的代码看起来像:

Let's rename it to is_a/2. Then your code looks like:

:- dynamic( is_a/2 ).

is_a(m1, house).
is_a(m1, thing).
is_a(m2, house).
is_a(m2, thing).
is_a(m3, niche).
is_a(m3, house).
is_a(m3, thing).
is_a(m4, car).
is_a(m4, mobile).
is_a(m4, house).
is_a(m4, thing).

然后您可以定义一个谓词来描述成对的结论和前提,如下所示:

Then you could define a predicate to describe pairs of conclusions and premises like so:

conclusion_premise(is_a(X, thing), is_a(X, house)).
conclusion_premise(is_a(X, house), is_a(X, niche)).

在此基础上,您可以定义 my_rule/2 来描述 CP 必须是一对相应的结论和前提,并且随后将两者都称为目标:

Building on this you could define my_rule/2 to describe that C and P must be a corresponding pair of conclusion and premise and to subsequently call both as goals:

my_rule(C,P) :-
   conclusion_premise(C,P),
   call(C),
   call(P).

现在您可以查询 my_rule/2 以搜索相应的结论-前提对:

Now you can query my_rule/2 to search for corresponding conclusion-premise pairs:

?- my_rule(Conclusion,Premise).
Conclusion = is_a(m1, thing),
Premise = is_a(m1, house) ;
Conclusion = is_a(m2, thing),
Premise = is_a(m2, house) ;
Conclusion = is_a(m3, thing),
Premise = is_a(m3, house) ;
Conclusion = is_a(m4, thing),
Premise = is_a(m4, house) ;
Conclusion = is_a(m3, house),
Premise = is_a(m3, niche) ;
false.