Raven
Raven

Reputation: 23

Finding complement of a set in prolog

suppose i've defined three clubs in Prolog:

club(football,   [john, mary, peter, jane]).
club(basketball, [peter, jane, tom, kim]).
club(dance,      [emily, andrew, john, jacob]).

now i wish to find the complement of football club from the combined three clubs (i.e answer should display [tom, kim,emily, andrew, jacob])

please write a code in prolog to perform the above task.

i tried to append the three lists and then subtract the football list from the combined list but i was getting multiple errors

Upvotes: -1

Views: 206

Answers (1)

TA_intern
TA_intern

Reputation: 2422

Let's imagine that I somehow had a relation club_member/2 like this:

?- club_member(C, M).
C = football, M = john ;
C = football, M = mary ;
C = football, M = peter ;
C = football, M = jane ;
C = basketball, M = peter ; % etc

You can redefine your rules or maybe figure out how to define a new rule that translates it at run time. Once you have it, union(A, B) is A ; B and complement as in A \ B is the set difference or A, \+ B. So:

?- setof(M,
       ( ( club_member(basketball, M)
         ; club_member(dance, M)
         ),
         \+ club_member(football, M)
       ),
       Members).
Members = [andrew, emily, jacob, kim, tom].

The parentheses look excessive :-( but cannot be avoided in that case.

In this particular case, if you assume that the union of all three is the universe, then the complement A' could be defined also as:

?- setof(M,
       C^( club_member(C, M),
           \+ club_member(football, M)
         ),
       Members).
Members = [andrew, emily, jacob, kim, tom].

Upvotes: 0

Related Questions