Prolog 计算排列

标签 prolog

我正在编写一个排列函数 [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/

相关文章:

linux - 在 GNU-Prolog 中,我可以 'catch' 一个 linux 信号吗?

arrays - 给定一个枢轴,如何在序言中分解列表?

Prolog,在终端中得到正确的答案,但在运行程序时得到错误的答案

prolog - 谓词必须对列表中的所有元素都为真

Prolog在2个单词中找到相似的字母

Prolog 时间重叠问题

prolog - 序言组合练习

list - Prolog中列表中连续相似元素的子列表

list - Prolog 中的子集

prolog - 为什么此序言查询同时为真和假?