Prolog - 通过演绎减少知识库

时间:2018-04-16 19:08:51

标签: prolog

我需要创建一个规则来搜索与my_rule匹配的事实。这些事实将用于改变知识库。 (my_rule (Conclusion, Premise))。

我从这个知识库开始:

:- dynamic( is/2 ).

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

my_rule( is( X, thing ), is( X, house ) ).
my_rule( is( X, house ), is( X, niche ) ).

当找到规则时,代码将搜索数据库中是否存在结论及其前提。

我不知道如何实现这一点,是的,这是为了做作业。 我只想要有人指出从哪里开始。

感谢。

1 个答案:

答案 0 :(得分:3)

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

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

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

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

我们将其重命名为is_a/2。然后您的代码如下:

:- 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).

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

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

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

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

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

?- 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.