Prolog中的动态谓词 [英] Dynamic predicate in Prolog

查看:36
本文介绍了Prolog中的动态谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用 Prolog,但我在使用动态谓词时遇到了这个问题 - 我没有得到正确的结果.

I have started using Prolog and I am having this problem with a dynamic predicate - I don't get the right result.

这是我的数据库:

:- dynamic mother/2.

mother(X,Y).

grandemother(X,Y) :- 
    mother(X,A),
    mother(A,Y).

这些是我得到的一些结果:

These are some of the results I get:

1 ?- assert(mother(alice,lise)).
true.

2 ?- assert(mother(lise,kate)).
true.

3 ?- grandemother(alice,X). % should only give X = kate.
true ;
X = lise ;
X = kate ;
true ;
X = kate.

4 ?- grandemother(alice,lise). % should only give false.
true ;
true ;
true ;
false.

5 ?- grandemother(X,kate). % should only give X = alice.
true ;
true ;
X = alice ;
X = alice ;
X = lise.

我真的不知道问题出在哪里,有什么想法吗?

I really don't know where the problem is, any ideas?

推荐答案

正如@lurker 在他的评论中所说的,问题是你的行 mother(X,Y).,直接在动态声明之后.

As @lurker said in his comment, the issue is your line mother(X,Y)., directly after the dynamic declaration.

为了准确地分解正在发生的事情,我将查看 grandemother(alice,X)(在您对 mother(alice,lise) 的断言之后)妈妈(莉丝,凯特)):

To break down exactly what's happening, I'll look at grandemother(alice,X) (after your asserts of mother(alice,lise) and mother(lise,kate)):

grandemother(alice,X) :- mother(alice,A),mother(A,X).
mother(alice,A) unifies with mother(X,Y). This leaves A unbound. 
mother(A,X) unifies with mother(X,Y). This leaves both A and X unbound.

因此,grandemother(alice,X) 无需绑定 X 即可成功.

Therefore, grandemother(alice,X) succeeds without having to bind X.

我们再次询问,这次:

mother(A,X) unifies with mother(alice,lise). (The second mother/2 fact.)

grandemother(alice,X) 成功,X 绑定到 lise.再问...

grandemother(alice,X) succeeds with X bound to lise. Ask again...

mother(A,X) unifies with mother(lise,kate).

X 是凯特.再次...

X is kate. Again...

mother(A,X) cannot be unified any more. Backtrack further...
mother(alice,A) unifies with mother(alice,lise).
mother(lise,X) unifies with mother(X,Y). X is unbound.

X 再次未绑定,所以我们只得到 true.再次...

X is unbound again, so we just get true. Again...

mother(lise,X) unifies with mother(lise,kate).

X 又是凯特.还有吗?

X is kate again. Any more?

mother(lise,X) cannot be unified any more. Backtrack further...
mother(alice,A) cannot be unified any more. Backtrack further...
No more backtracking to be done, so there are no more results.

所以我们没有得到更多的结果.

So we get no more results.

正如@lurker 所指出的,解决方案是删除mother(X,Y).,这样就不会发生这种未绑定的行为.

The solution, as @lurker pointed out, is to remove mother(X,Y)., so that this unbound behaviour cannot occur.

这篇关于Prolog中的动态谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆