让所有兄弟姐妹在Prolog中聚会

时间:2016-07-05 16:43:26

标签: prolog

我正在尝试将所有兄弟姐妹聚集在一起代码:

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]]

1 个答案:

答案 0 :(得分: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)

相同