我正在编写一个排列函数 [a,b]-->[[[a], [b]], [[a, b]]
到目前为止我已经做到了,但它不起作用。
perm([],[]).
perm(L,[H|T]) :- append(V,[H|U],L), append(V,U,W), perm(W,T).
最佳答案
根据您的示例,看起来您可能实际上想要 powerset ,而不是给定列表的排列。
例如,[a,b]
的幂集是集合 {[a,b]
, [a]
, [b]
,[]
}。
要计算 Prolog 中项目列表的幂集,请查看 this answer作者:@gusbro。如果这对您有帮助,还请为该答案点赞。
如果您想要一次列表 L
的 powerset 的所有解决方案,您可以将对 powerset/2
的调用包装在 findall/3
像这样调用:
?- findall(S, powerset(L, S), Ss).
另一方面,如果您需要分区(正如您在之前的一次编辑中提到的那样),请考虑以下事项:
partition(L, PL) :-
partition(L, [], PL).
partition([], [], []).
partition([X|Xs], As, R) :-
% add X into the new partition...
append(As, [X], NewAs),
partition(Xs, NewAs, R).
partition(L, [A|As], [[A|As]|R]) :-
% ...or, collect the current non-empty partition
partition(L, [], R).
谓词 partition/2
接受一个列表并返回所有分区,如您所描述的。例如:
?- partition([a,b,c],L).
L = [[a, b, c]] ;
L = [[a, b], [c]] ;
L = [[a], [b, c]] ;
L = [[a], [b], [c]] ;
false.
关于Prolog 计算排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12824685/