I have a set of possibilities in a Prolog script and want to find the largest set, where a particular predicate applied to all pairs of the list evaluates true.
A simplified example would be a set of people, and you want to find the largest group where all of them are mutual friends. So, given:
% Four-way friend CIRCLE
link(tom, bill).
link(bill, dick).
link(dick, joe).
link(joe, tom).
% Four-way friend WEB
link(jill, sally).
link(sally, beth).
link(beth, sue).
link(sue, jill).
link(jill, beth).
link(sally, sue).
% For this example, all friendships are mutual
friend(P1, P2) :- link(P1, P2); link(P2, P1).
The possible matches should be (presenting each pair alphabetically for clarity):
% the two-person parts of both sets :
[bill, tom], [bill, dick], [dick, joe], [joe, tom],
[jill, sally], [beth, sally], [beth, sue], [jill, sue],
[beth, jill], [sally, sue]
% any three of the web :
[beth, jill, sally], [beth, sally, sue], [beth, jill, sue]
% and the four-person web :
[beth, jill, sally, sue]
I can find all the two-person matches with:
% Mutual friends?
friendCircle([Person1, Person2]) :-
friend(Person1, Person2),
% Only keep the alphabetical-order set:
sort([Person1, Person2], [Person1, Person2]).
But then I get snagged trying to find the larger sets:
friendCircle([Person1|Tail]) :-
friendWithList(Person1, Tail),
Tail = [Person2|Tail2],
% Only keep if in alphabetical order:
sort([Person1, Person2], [Person1, Person2]),
friendWithList(Person2, Tail2).
% Check all members of the list for mutual friendship with Person:
friendWithList(Person, [Head|Tail]) :-
friend(Person, Head), % Check first person in list
friendWithList(Person, Tail). % Check rest of list
But when I run that, after enumerating the two-person lists, Prolog just hangs and eventually runs out of stack space. What am I doing wrong?
What I'm trying to do is walk the web, which for a five-friend web would be checking each of these pairs for friend status:
(1,2) (1,3), (1,4), (1,5) % Compare element 1 with the rest of the list
(2,3), (2,4), (2,5) % Remove element 1 and repeat
(3,4), (3,5)
(4,5)
Which is what I thought my two friendsWithList/2
calls in the friendCircle/1
rule were doing.
sort([Person1, Person2], [Person1, Person2])
is just a complicated way of sayingPerson1 @=< Person2
. – Fred Foo?- Person1 = john, sort([Person1, Person2], [Person1, Person2]).
which givesPerson2 = john.
– false