Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Intersection of Set



In Prolog, we generally represents Sets using List. In this chapter, we're discussing how to get Intersection of two sets by defining a predicate.

Getting Intersection of Sets represented by a List

Let us define a clause called list_intersection(L1,L2,L3), So this will take L1 and L2, and perform Intersection operation, and store the result into L3. Intersection will return those elements that are present in both lists. So L1 = [a,b,c,d,e], L2 = [a,e,i,o,u], then L3 = [a,e]. Here, we will use the list_member() clause to check if one element is present in a list or not.

Program (list_set.pl)

list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_intersect([X|Y],Z,[X|W]) :-   list_member(X,Z), list_intersect(Y,Z,W).
list_intersect([X|Y],Z,W) :-   \+ list_member(X,Z), list_intersect(Y,Z,W).
list_intersect([],Z,[]).

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_set.pl').
compiling D:/TP Prolog/Sample Codes/list_set.pl for byte code...
D:/TP Prolog/Sample Codes/list_set.pl:5: warning: singleton variables [Z] for list_intersect/3
D:/TP Prolog/Sample Codes/list_set.pl compiled, 4 lines read - 1510 bytes written, 4 ms

yes
| ?- list_intersect([a,b,c,d,e],[a,e,i,o,u],L3).

L3 = [a,e] ? 

yes
| ?- list_intersect([a,b,c,d,e],[],L3).

L3 = []

yes
| ?- 

Explanation

  • list_member(X,[X|_]) represents the base case checking a member where element is head of the list.

  • list_member(X,[_|TAIL]) :- list_member(X,TAIL) represents the case checking a member where element is in the tail of the list.

    • list_member(X,[_|TAIL]) is to check X in the tail of the list.

    • list_member(X,TAIL) is a recursive call checking X in the tail of the List.

  • list_intersect([X|Y],Z,[X|W]) :- list_member(X,Z), list_intersect(Y,Z,W). returns W as a intersection of first two Sets where X is head and is common element of both sets.

    • list_intersect([X|Y],Z,[X|W]) is to divide the first list where X represents the head of the list and Y represents the tail of the list. Z is second Set. X|W is intersection of sets.

    • list_member(X,Z) checks the X to be member of Z. If X is member of Z then Intersection is calculated on Y and Z excluding X as it will be added as head to the intersection set.

  • list_intersect([X|Y],Z,W) :- \+ list_member(X,Z), list_intersect(Y,Z,W). returns W as a intersection of first two Sets where X is not a common head element.

    • list_intersect([X|Y],Z,W) is to divide the first list where X represents the head of the list and Y represents the tail of the list. Z is second Set. W is intersection of set.

    • list_member(X,Z) checks the X to be member of Z. If X is member of Z then Intersection is calculated on Y and Z including X being not a member of Z set.

Advertisements