Create a prolog program to compute the union the intersectio

Create a prolog program to compute the union, the intersection, the difference of two sets.

Solution

Concept of Set Operations with Prolog Program with their examples results :

union of set X and set Y: giving a set containing elements either in X or in Y.


union([],X,X).
union([X|R],Y,Z) :- member(X,Y), !, union(R,Y,Z).
union([X|R],Y,[X|Z]) :- union(R,Y,Z).

Examples

Success:
union([10,20,30],[10,30],L). (gives L=[20,10,30]).

Fail:
union([10,20,30,20],[10,30],[10,20,30]). % repeated elements

intersection of X and Y: giving a set containing elements both in X and in Y.

intersect([],Y,[]).
intersect([X|R],Y,[X|Z]) :- member(X,Y),!,intersect(R,Y,Z).
intersect([X|R],Y,Z) :- non_member(X,Y),!,intersect(R,Y,Z).

Examples

Success:
intersection([11,22],[22,33],L). (gives L=[22]).
intersection([a,d],[a,b,c],[a]).

Fail:
intersection([a,b],[a,b],[b]).


difference of X and Y: giving a set containing elements in Y and not in Y


difference([],Y,[]).
difference([X|R],Y,Z) :- member(X,Y),!,difference(R,Y,Z).
difference([X|R],Y,[X|Z]) :- difference(R,Y,Z).

Examples

Success:
difference([21,22,23,24],[21],R). (gives R=[22,23,24]).
difference([21,22,23],[23,24],R). (gives R=[21,22]).
difference([21,21,22,23],[22],[21,21,23]).
Fail:
difference([21,21,22,23],[21],[21,22,23]). % Fails - List2 and
% Remainder share elements

Create a prolog program to compute the union, the intersection, the difference of two sets.SolutionConcept of Set Operations with Prolog Program with their exam

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site