2015-10-21 100 views
0

鑑於這些事實:家長查詢不返回所有parentships

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

正如你可以看到沃倫和maryalice是傑裏,斯圖爾特和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 ; 
........ 

哪裏沃倫和斯圖爾特和maryalice和斯圖爾特的父母的想念(並且還停留在某種循環!)。

請幫我一把!

回答

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 
| ?- 
+0

非常感謝您的回覆! –