Search code examples
prolog

Prolog Subset Return Values To List


I'm trying to return the subsets of a certain list in another list to do some operations on them, my code for finding the subsets is as follows:

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

but this code only prints the subsets on the screen and whenever I try to use append to append each subset in another list, the code does not work as I expect it to.

one of the ways I tried to use append:

listSubset([] , [], AllSubSets).
listSubset([Head|Tail] , [Head|Subset], AllSubSets) :- 
    appendx([[Head|Subset]], AllSubSets, NewAllSubSets),
    listSubset(Tail, Subset, NewAllSubSets).
listSubset([Head|Tail] , Subset, AllSubSets) :-
    listSubset(Tail, Subset, AllSubSets).
    
appendx([],List,List).
appendx([H|T],List,[H|T2]) :- 
    appendx(T,List,T2).

Solution

  • To collect all subsets of a set in a list, just ask:

    ?- findall(S, listSubset([a,b,c],S), L).
    L = [[a, b, c], [a, b], [a, c], [a], [b, c], [b], [c], []].