Reputation: 443
**FACTS**
player(milan,[seedorf,zambrotta,gattuso]).
player(inter,[seedorf,ronaldo,zambrotta]).
player(realmadrid,[seedorf,zidane,ronaldo]).
i wanna create a predicate such that :
find (TEAM, PLAYERS)
and if my goal is find(X,Y) it will returns List of teams,X, and List of players,Y, without any duplicates... Like below:
X=[milan], Y=[seedorf,zambrotta,gattuso];
X=[inter], Y=[seedorf,ronaldo,zambrotta];
X=[realmadrid], Y=[seedorf,zidane,ronaldo];
X=[milan,inter] Y=[seedorf,zambrotta];
X=[milan,realmadri] Y=[seedorf];
...
X=[milan,inter,realmadrid] Y=[seedorf];
...
i try to do this with but it gives "ERROR: Out of local stack", If i do not use remove_dups predicate, The list of teams,"X", would have duplicates and program could not stop... keep going like X=[milan,milan,milan,milan,inter] .... How can i correct this code. ?:
find([X], Y) :- player(X1, Y),remove_dups(X1,X).
find([X|Xs], Y) :- player(X1, Y0),find(Xs, Y3), intersection(Y0, Y3, Y),remove_dups(X1,X).
remove_dups([],[]).
remove_dups([First|Rest],NewRest):-member(First, Rest),remove_dups(Rest, NewRest).
remove_dups([First|Rest],[First|NewRest]):-not(member(First, Rest)),remove_dups(Rest, NewRest).
Thanks a lot...
Upvotes: 0
Views: 1244
Reputation: 41290
When you do pattern matching on a list of Xs
, it always puts in the same value of milan
so there are a lot of duplication. You can avoid it by first ensuring no duplication in the list of Xs
and finding corresponding players:
subset([], []).
subset(Xs, [_|Ys]) :- subset(Xs, Ys).
subset([X|Xs], [X|Ys]) :- subset(Xs, Ys).
allteams(Ts) :- findall(T, player(T, _), Ts).
teams(T) :- allteams(Ts), subset(T, Ts).
find1([T], L) :- player(T, L).
find1([T|Ts], L) :- player(T, L0), find1(Ts, L1), intersection(L0, L1, L).
find(X, Y) :- teams(X), find1(X, Y).
Here I find a set of all teams first and try to find subsets satisfying the condition.
Upvotes: 1