2016-07-05 21 views
2

我試圖讓所有的兄弟姐妹一起在下面的代碼:讓所有的兄弟姐妹一起在序言

father_child(tom, sally). 
father_child(john, alfred). 
father_child(george, peter). 
father_child(tom, dick). 
father_child(john, harry). 
father_child(george, eliz). 
father_child(tom, james). 
father_child(john, ron). 
father_child(george, hermoine). 

siblings(X, Y):- father_child(Z, X), father_child(Z, Y), X @< Y. 

?- findall([X,Y], siblings(X,Y), L). 
L = [[alfred, harry], [alfred, ron], [dick, sally], [dick, james], [harry, ron], [eliz, peter], [eliz, hermoine], [james|...], [...|...]]. 

但它僅給出了對。如果我不知道有多少兄弟姐妹在那裏,我想要列出兄弟姐妹名單(如下),我該如何管理?

[[a, b, c], [d, e], [x, y, z, w]] 

回答

3

你只需要使用setof/3bagof/3。這是一個很好的例子,那些findall/3不能(很容易)做的事情。一無所有定義的father_child/2表:

?- bagof(C, father_child(F, C), Siblings). 
F = george, 
Siblings = [peter, eliz, hermoine] ; 
F = john, 
Siblings = [alfred, harry, ron] ; 
F = tom, 
Siblings = [sally, dick, james]. 

當然,你可以窩這裏面一個findall/3

?- findall(Siblings, 
      bagof(C, father_child(F, C), Siblings), 
      Ss). 
Ss = [[peter, eliz, hermoine], [alfred, harry, ron], [sally, dick, james]]. 

你應該嘗試看看,如果你使用bagof/3代替findall/3會發生什麼。 (提示:使用findall/3像這樣寫bagof(Siblings, F^bagof(C, father_child(F, C), Siblings), Ss)

+0

完美,這正是我想要的。謝謝。 – rnso