Prolog:如何在下一个规则中使用一个规则的答案

时间:2016-11-24 13:33:14

标签: prolog duplicates

我正在努力弄清楚为什么这不起作用。使用SWI-Prolog,我试图:

  1. 使用people(List)规则从女性(姓名,eee)事实中创建女性姓名列表(名为List)。
  2. 使用复制(列表,元素)规则查找人员生成的列表中的任何重复名称(列表)
  3. 人和重复规则都可以自行运行,但是当我尝试将它们组合起来时,程序总是返回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).
    

    非常感谢任何帮助!

1 个答案:

答案 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