Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the list [1] not included in the answer P = [[]]? Prolog

Tags:

prolog

I'm learning Prolog but I came across this questions when learning about database manipulation. when I ask the Prolog interpreter:

 findall(X,subset(X,[1]),P).

the only subset give is

P = [[]].

Why is this?

like image 216
Numbers123 Avatar asked Jan 11 '21 17:01

Numbers123


People also ask

How do I use a list in Prolog?

In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.

What are lists in Prolog?

Lists are a common data structure in computer programming. In Prolog, lists are represented as a tree consisting of structures that have no arguments, an empty list, or two arguments: a head and a tail. The head is a used to store a particular term in the list and the tail is recursively the rest of the list.

How do I print a list in Prolog?

print all elements of a list ?-print_list([a,b,c]). a b c print_list([]):-nl. %nl = newline print_list([H|T]):-write(H),write(' '),print_list(T).

Is Empty list Prolog?

A list is either empty or it is composed of a first element (head) and a tail, which is a list itself. In Prolog we represent the empty list by the atom [] and a non-empty list by a term [H|T] where H denotes the head and T denotes the tail.


1 Answers

In SWI-Prolog, the predicate subset/2 is defined as:

% subset(+SubSet, +Set)

subset([], _) :- !.
subset([E|R], Set) :-
    memberchk(E, Set),
    subset(R, Set).

To obtain the desired result, you can use the following alternative definition:

% sub_set(?SubSet, +Set)

sub_set([], []).
sub_set(SubSet, [_|Set]) :- sub_set(SubSet, Set).
sub_set([X|SubSet], [X|Set]) :- sub_set(SubSet, Set).

Examples:

?- sub_set(S,[a,b,c]).
S = [] ;
S = [c] ;
S = [b] ;
S = [b, c] ;
S = [a] ;
S = [a, c] ;
S = [a, b] ;
S = [a, b, c] ;
false.

?- sub_set([a,c],[a,b,c]).
true ;
false.

?- findall(SubSet, sub_set(SubSet,[1]), PowerSet).
PowerSet = [[], [1]].
like image 140
slago Avatar answered Oct 24 '22 13:10

slago