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?
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.
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.
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).
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.
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]].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With