2016-07-05 50 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