Gnu Prolog nutrition modification

So, I got this for poweret:

powerset([], []). powerset([H|T], P) :- powerset(T,P). powerset([H|T], [H|P]) :- powerset(T,P). 

This generates all list sets. Is it possible to generate all sets in list order.

Example:

 List = [a,b,c] 

I want to receive

 [a],[a,b],[a,b,c],[b],[b,c],[c] 

Note that there is no [a,c] in this list of subsets, since these are subsets starting from the left and going to the right.

I tried using a combination of add and recursion, but that didn't work the way I wanted it. This is a bit difficult at the moment.

Thanks.

+4
source share
4 answers

What about

 powerset(L, [H|T]):- append([H|T], _, L). powerset([_|L], P):- powerset(L, P). 
+6
source

You want all substrings of a subsequence ( definition ). Grams (DCG) are best suited for this:

 seq([]) --> []. seq([E|Es]) --> [E], seq(Es). ... --> [] | [_], ... . ?- Es = [_|_], phrase((..., seq(Es), ...), [A,B,C]). Es = [A] ; Es = [A, B] ; Es = [A, B, C] ; Es = [B] ; Es = [B, C] ; Es = [C] ; false. 

(SWI Prolog)

+3
source

I know this old post, but I am not going to update it for no reason. the answer, which is accepted with all due respect, generates all subsets separably and does not generate a set of credentials.

a few days ago, I tried to implement the powerSet/2 predicate without using the built-in bagof/2 predicate. but even with bagof/2 and setof/2 this is not a very simple task for beginners (generating the entire subset is separable is another problem and is much simpler). therefore, after implementing the solution, I thought it was better to put it here so that people who were looking for this topic were not mistaken.

My solution (without bagof/2 )

  generate (X, [Y], [[X | Y]]).

 generate (X, S, P): -
         S = [H |  T]
         append ([X], H, Temp),
         generate (X, T, Rest),
         append ([Temp], Rest, P),!.

 powerSet ([], [[]]).

 powerSet (Set, P): -
         Set = [H |  T]
         powerSet (T, PsT),
         generate (H, PsT, Ps),
 % write ('trying to push'), print (H), write ('to'),
 % write ('all elements of powerset of'), print (T), write ('which is'),
 % print (PsT), nl,
 % write ('and the result is'), print (Ps), nl, nl,
         append (Ps, PsT, P),!.

the code will be understood by referring to the comments.

another solution is available here , which uses the built-in predicate bagof/3 .

perhaps now it would be more useful.

+2
source

How about this:

 powerset(A,B):- append(A,_,B); append(_,A,B). test():- setof(X,powerset(X,[1,2,3]),L), writeln(L). 
0
source

All Articles