Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Union of Set



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

Getting Union of Sets represented by a List

Let us define a clause called list_union(L1,L2,L3), So this will take L1 and L2, and perform Union on them, and store the result into L3. As you know if two lists have the same element twice, then after union, there will be only one. So we need another helper clause to check the membership.

Program (list_set.pl)

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

Note − In the program, we have used (\+) operator, this operator is used for NOT.

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 compiled, 4 lines read - 1484 bytes written, 6 ms

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

L3 = [b,c,d,a,e,i,o,u] ? 

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

L3 = [a,b,c,d,e,1,2]

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_union([X|Y],Z,W) :- list_member(X,Z),list_union(Y,Z,W) returns W as a union of first two Sets.

    • list_union([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 union of set.

    • list_member(X,Z) checks the X to be member of Z. If X is member of Z then Union is calculated on Y and Z excluding X being already member of Z set.

  • list_union([X|Y],Z,[X|W]) :- \+ list_member(X,Z), list_union(Y,Z,W) returns W as a union of first two Sets including X as head element.

    • list_union([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 union of set.

    • list_member(X,Z) checks the X to be member of Z. If X is member of Z then Union is calculated on Y and Z excluding X being already member of Z set.

Advertisements