我有此代码:
likes(ali, football).
likes(ali, tennis).
likes(ahmad, tennis).
likes(ahmad, handball).
likes(samir, handball).
likes(samir, swimming).
likes(khaled, horseriding).
friends(P1, P2):-
likes(P1, G1), likes(P2, G1), P1\=P2.
输入为:
friends(X, Y)
输出为
X = ali,
Y = ahmad
X = ahmad,
Y = ali
X = ahmad,
Y = samir
X = samir,
Y = ahmad
如果可能的话,如何删除此重复。
答案 0 :(得分:1)
您可以添加在绑定变量时应测试的谓词:when/2:
when(ground(X+Y), X @< Y), friends(X,Y).
一旦术语X+Y
中没有更多的自由变量,请确保X @< Y
:
?- when(ground(X+Y), X @< Y), test:friends(X,Y).
X = ahmad,
Y = ali ;
X = ahmad,
Y = samir ;
这对您的测试很有用,但总的来说,我认为不需要删除重复项。
答案 1 :(得分:1)
由于类似的answer具有所有说明,因此我仅在此处提供代码。
friend(P3,P4) :-
likes(P1,G1),
likes(P2,G1),
P1 \= P2,
normalize(P1,P2,P3,P4).
normalize(P1,P2,P1,P2) :- P1 @> P2.
normalize(P1,P2,P2,P1) :- P1 @=< P2.
friends(List) :-
setof((P1,P2), (P1,P2)^friend(P1,P2), List).
示例:
?- friends(List).
List = [(ali, ahmad), (samir, ahmad)].