Prolog スクリプトに一連の可能性があり、リストのすべてのペアに適用される特定の述語が true と評価される最大のセットを見つけたいと考えています。
単純化された例は、一連の人々であり、すべてが相互の友人である最大のグループを見つけたいと考えています。したがって、与えられた:
% 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 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]
2 人で一致するものはすべて次のように見つけることができます。
% Mutual friends?
friendCircle([Person1, Person2]) :-
friend(Person1, Person2),
% Only keep the alphabetical-order set:
sort([Person1, Person2], [Person1, Person2]).
しかし、その後、より大きなセットを見つけようとして引っ掛かります。
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
しかし、それを実行すると、2 人のリストを列挙した後、Prolog がハングアップし、最終的にスタック スペースが不足します。私は何を間違っていますか?
私がやろうとしているのは、ウェブを歩くことです。これは、5人の友達のウェブの場合、これらのペアのそれぞれの友達のステータスをチェックすることになります:
(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)
これは、ルールfriendsWithList/2
内の 2 つの呼び出しが行っていると思っていたことです。friendCircle/1