Prolog计算排列

Joh*_*ohn 4 prolog

我正在写一个排列函数[a,b] - > [[[a],[b]],[[a,b]]

到目前为止,我有这个,但它不起作用.

perm([],[]).
perm(L,[H|T]) :- append(V,[H|U],L), append(V,U,W), perm(W,T).
Run Code Online (Sandbox Code Playgroud)

sha*_*rky 5

举个例子,看起来你可能实际上想要给定列表的powerset而不是排列.

例如,幂的[a,b]是集合{ [a,b],[a],[b],[]}.

要计算Prolog中项目列表的powerset,请查看@gusbro的这个答案.如果这对您有所帮助,请同意请回答.

如果你想同时获得列表的powerset的所有解决方案L,你可以在这样的调用powerset/2中包含findall/3调用:

?- findall(S, powerset(L, S), Ss).
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您在分区之后(正如您在之前的编辑中提到的那样),请考虑以下事项:

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).
Run Code Online (Sandbox Code Playgroud)

partition/2正如您所描述的,谓词采用列表并返回所有分区.例如:

?- partition([a,b,c],L).
L = [[a, b, c]] ;
L = [[a, b], [c]] ;
L = [[a], [b, c]] ;
L = [[a], [b], [c]] ;
false.
Run Code Online (Sandbox Code Playgroud)