Reputation: 225
I am supposed to write a program in Prolog which when given a list,returns the permutation of its powerset.
one thing I forgot to mention: I already have a predicate that reverses a list: deep_reverse(List,RevList).
for example: ?-sublist_perm([a,b,c],X).
will return:(duplicates are allowed)
X = [] ;
X = [c] ;
X = [b] ;
X = [b, c] ;
X = [c, b] ;
X = [a] ;
X = [a, c] ;
X = [c, a] ;
X = [a, b] ;
X = [b, a] ;
X = [a, b, c] ;
X = [b, a, c] ;
X = [b, c, a] ;
X = [a, c, b] ;
X = [c, a, b] ;
X = [c, b, a]
Upvotes: 1
Views: 1733
Reputation: 26043
You ask two things in one question: How to get all sublists and how to permutate a list:
sublist_perm(In, Out) :-
sublist(In, Temp),
permutation(Temp, Out).
sublist([], []).
sublist([_|XS], YS) :-
sublist(XS, YS).
sublist([X|XS], [X|YS]) :-
sublist(XS, YS).
See also: man page for permutation/2.
findall(X, sublist_perm([a,b,c], X), XS),
XS = [[],[c],[b],[b,c],[c,b],[a],[a,c],[c,a],[a,b],[b,a],
[a,b,c],[b,a,c],[b,c,a],[a,c,b],[c,a,b],[c,b,a]].
Upvotes: 4