prolog中的父查询不会返回所有父项

时间:2015-10-21 11:19:24

标签: prolog

鉴于以下事实:

male(jerry).
male(stuart).
male(warren).
male(peter).
female(kather).
female(maryalice).
female(ann).
brother(jerry,stuart).
brother(jerry,kather).
brother(peter, warren).
sister(ann, maryalice).    
sister(kather,jerry).
parent_of(warren,jerry).
parent_of(maryalice,jerry).

你可以看到warren和maryalice是jerry,stuart和kather的父母。为了使查询parent_of(X,Y).返回

,我需要执行哪些规则
X=warren, Y=jerry
X=warren, Y=stuart
X=warren, Y=kather
X=maryalice, Y=jerry
X=maryalice, Y=stuart
X=maryalice, Y=kather

即所有的父母关系?

我试过了

parent_of(X,Y) :- parent_of(X,C), sibling(Y,C), X \= Y.
sibling(C,OC) :- brother(C,OC), C \= OC.
sibling(C,OC) :- sister(C,OC), C \= OC.

但查询parent_of(X,Y).会返回此

X = warren,
Y = jerry ;
X = maryalice,
Y = jerry ;
X = warren,
Y = kather ;
X = maryalice,
Y = kather ;
X = warren,
Y = jerry ;
X = maryalice,
Y = jerry ;
X = warren,
Y = kather ;
X = maryalice,
Y = kather ;
X = warren,
Y = jerry ;
X = maryalice,
Y = jerry ;
X = warren,
Y = kather ;
X = maryalice,
Y = kather ;
X = warren,
Y = jerry ;
X = maryalice,
Y = jerry ;
X = warren,
Y = kather ;
........

warren和stuart以及maryalice和stuart之间的父母身份是错过的(并且它也被卡在某种循环中!)。

请帮帮我!

1 个答案:

答案 0 :(得分:1)

我会将事实parent_of与谓词分开:

is_parent_of(X, Y) :- parent_of(X, Y).
is_parent_of(X, Y) :- parent_of(X, C), sibling(C, Y).

我认为你不需要C \= Y,因为你的事实没有任何人是他们自己的兄弟,所以支票是多余的。同样,检查以确保我们没有捕获某人是他们自己的父母是多余的。

使用上述规则和您当前的数据库示例,您可以获得所需的结果:

| ?- is_parent_of(X, Y).

X = warren
Y = jerry ? ;

X = maryalice
Y = jerry ? ;

X = warren
Y = stuart ? ;

X = warren
Y = kather ? ;

X = maryalice
Y = stuart ? ;

X = maryalice
Y = kather ? ;

(1 ms) no
| ?-