Prolog中的动态谓词

时间:2017-02-20 21:14:45

标签: prolog

我已经开始使用Prolog,我遇到了动态谓词的问题 - 我没有得到正确的结果。

这是我的数据库:

:- dynamic mother/2.

mother(X,Y).

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

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

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.

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

1 个答案:

答案 0 :(得分:0)

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

要准确分解正在发生的事情,我会查看grandemother(alice,X)(在您声明mother(alice,lise)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.

我们再次询问,这一次:

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

grandemother(alice,X)成功,X绑定了lise。再问一次......

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

X是凯特。再次...

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。再次...

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

X又是凯特。还有吗?

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.

所以我们得不到更多结果。

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

相关问题