Permutations of power set in Prolog

2019-06-03 15:29发布

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]

标签: prolog
1条回答
乱世女痞
2楼-- · 2019-06-03 15:57

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]].
查看更多
登录 后发表回答