在这种情况下如何避免重复

时间:2014-03-26 19:01:40

标签: prolog

我现在有这个工作,因为我想要它:

male(roelof).
male(mans). 
male(ronald).
male(jan).

female(chantal).
female(marie).
female(gerda).
female(dagmar).
female(denise).
female(kimberly).

parent(mans,gerda).
parent(mans,roelof).
parent(marie,gerda).
parent(marie,roelof).
parent(dagmar,denise).
parent(dagmar,kimberly).
parent(ronald,denise).
parent(ronald,kimberly).
parent(chantal,tamara).
parent(roelof,tamara).
parent(jan,chantal).
parent(jan,dagmar).

% Looks for the father of a child. Gives the name if found. 
% if no father is  found then it gives false
father_child(Child) :-
parent(Father, Child),
 male(Father).

% Looks for the mother of a child. Gives the name if found. 
% if no mother is  found then it gives false
mother_child(Child) :-
parent(Mother, Child),
female(Mother).

% Looks if two person has the same father. 
% Gives true if a person is a father of both persons 
% Gives false if no person is a father of both persons.
same_father(Child, Sibling) :-
  parent(Father,Child),
  parent(Father,Sibling),
  male(Father).

% Looks if two person has the same mother. 
% Gives true if a person is a mother of both persons 
% Gives false if no person is a mother of both persons.
same_mother(Child, Sibling) :-
  parent(Mother,Child),
  parent(Mother,Sibling),
  female(Mother).

% Looks if there are siblings of a person. 
% Persons are siblings if they have the same father or
% if they have the same mother and not the same father.
siblings(X,Y) :-
       (   same_father(X, Y),
            X \= Y
        ;   same_mother(X, Y),
        \+ same_father(X, Y)
    ).

% Displays the output of siblings(X,Y) and takes care that 
% there are no duplicates.
display_siblings(Person) :-
      findall(Person - Y, (siblings(Person,Y), Y @< Person), Sibs),
      display_the_siblings(Sibs).

% Display a message if there are no siblings found. 
display_the_siblings([]) :-
       write('Er zijn geen zussen/broers bekend').

display_many([]).
display_many([H|T]):-
        writeln('Many elements '-H), display_many(T).

display_the-siblings([X]):- better_display([X]),!.
display_the_siblings([H|T]):- better_display([H|T]).

better_display([X]):-
    writeln('Single Element '-X).
better_display([X,Y|T]):-
    writeln('Many elements '-X), display_many([Y|T]).

但在这种情况下,display_siblings(Kimberly)为false,因为kimberly @< denise失败。 我是否会将规则设为Y @< Person,然后display_siblings(kimberly)有效但display(gerda)失败。

任何人都想摆脱这种混乱?

鲁洛夫

2 个答案:

答案 0 :(得分:0)

看看

apropos(setof).
apropos(findall).
apropos(member).

这些组合可以删除重复项。

答案 1 :(得分:0)

你可以试试这样的事情

display_siblings(Person) :-
    setof(Pair, (siblings(Person,Y), sib_pair(Person, Y, Pair)), Sibs),
    display_the_siblings(Sibs).

sib_pair(Person, Sib, Person-Sib) :-
    Person @< Sib.
sib_pair(Person, Sib, Sib-Person) :-
    Person @> Sib.