Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Subset of Set



In Prolog, we generally represents Sets using List. In this chapter, we're discussing how to get subset from a set by defining a predicate.

Getting Subset of a Set represented by a List

We will try to write a clause that will get all possible subsets of a given set. So if the set is [a,b], then the result will be [], [a], [b], [a,b]. To do so, we will create one clause, list_subset(L, X). It will take L and return each subsets into X. So we will proceed in the following way −

  • If list is empty, the subset is also empty.

  • Find the subset recursively by retaining the Head, and

  • Make another recursive call where we will remove Head.

Program (list_set.pl)

list_subset([],[]).
list_subset([Head|Tail],[Head|Subset]) :- list_subset(Tail,Subset).
list_subset([Head|Tail],Subset) :- list_subset(Tail,Subset).

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:3: warning: singleton variables [Head] for list_subset/2
D:/TP Prolog/Sample Codes/list_set.pl compiled, 2 lines read - 653 bytes written, 4 ms

(16 ms) yes
| ?- list_subset([a,b],X).

X = [a,b] ? ;

X = [a] ? ;

X = [b] ? ;

X = []

yes
| ?- list_subset([x,y,z],X).

X = [x,y,z] ? a

X = [x,y]

X = [x,z]

X = [x]

X = [y,z]

X = [y]

X = [z]

X = []

(16 ms) yes
| ?- 

Explanation

  • list_subset([],[]) represents the base case of the recursive call. In case list is empty, only subset is an empty list.

  • list_subset([Head|Tail],[Head|Subset]) :- list_subset(Tail,Subset) represents the subsets with head element.

    • list_subset([Head|Tail],[Head|Subset]) is to divide the first list where Head represents the head of the list and Tail represents the tail of the list.

    • list_subset(Tail,Subset) returns the subset by retaining the head.

  • list_subset([Head|Tail],Subset) :- list_subset(Tail,Subset). represents the subsets without head element.

    • list_subset([Head|Tail],Subset) is to divide the first list where Head represents the head of the list and Tail represents the tail of the list.

    • list_subset(Tail,Subset) returns the subset by removing the head.

Advertisements