我正在努力弄清楚为什么这不起作用。使用SWI-Prolog,我试图:
人和重复规则都可以自行运行,但是当我尝试将它们组合起来时,程序总是返回false,在使用carol的情况下,应该返回true。
female(carol,eee).
female(clare,eee).
female(mel,eee).
female(grace,eee).
female(clare,eee).
female(carol,eee).
%% duplicate(List, Element) is true for every matching pair of _Element_ in _List_
duplicate([First|Rest], Element) :-
duplicate_1(Rest, First, Element).
% First occurrence
duplicate_1([This|Rest], X, X) :- % first occurrence
duplicate_2(Rest, This, X).
duplicate_1([This|Rest], _, X) :- % look further for first occurrence
duplicate_1(Rest, This, X).
% Second occurrence
duplicate_2(_, X, X). % second occurrence
duplicate_2([This|Rest], _, X) :- % look further for second occurrence
duplicate_2(Rest, This, X).
people(List) :- findall(X, female(X,eee), List).
我正试图进入终端:
?- people(Y), duplicate(Y, carol).
非常感谢任何帮助!
答案 0 :(得分:2)
您需要在找到重复项后停止递归调用:
female(carol,eee).
female(clare,eee).
female(mel,eee).
female(grace,eee).
female(clare,eee).
female(carol,eee).
%% duplicate(List, Element) is true for every matching pair of _Element_ in _List_
duplicate([First|Rest], Element) :-
duplicate_1(Rest, First, Element).
% First occurrence
duplicate_1([This|Rest], X, X) :- % first occurrence
duplicate_2(Rest, This, X), !.
duplicate_1([This|Rest], _, X) :- % look further for first occurrence
duplicate_1(Rest, This, X).
% Second occurrence
duplicate_2(_, X, X):-!. % second occurrence
duplicate_2([This|Rest], _, X) :- % look further for second occurrence
duplicate_2(Rest, This, X).
people(List) :- findall(X, female(X,eee), List).
阅读(!)cut。