如何在 Prolog 中排列由子列表和原子组成的列表的元素

How to permute in Prolog the elements of a list composed of sub-list and atoms

让我们考虑列表,例如 L=[[7,3,4],9,[4,5],[1,3,5],4],其中组件可以是列表或原子。如何产生这种类型的排列结果:

R = [[7, 3, 4], 9, [4, 5], [1, 3, 5], 4] 
R = [[7, 4, 3], 9, [5, 4], [1, 3, 5], 4] 
R = [[7, 4, 3], 9, [4, 5], [1, 5, 3], 4] 
....

事实上,我们想要 L 的子列表的所有可能排列,而原子应该保持不变。

我写了一个经典谓词 permutation(OriginalList,PermutedList),以及一个将 maplist 函数应用于此排列谓词的 allperm 谓词:

permutation([],[]).

permutation(L,[T|Q]) :-
    select(T,L,L1),
    permutation(L1,Q).

/*L is the list to permute, R the result*/
allperm(L,R) :-
    maplist(permutation,L,R).

仅在L由列表组成的特殊情况下起作用,当L是异构(原子和列表)时不起作用。

您能否提供提示或解决方案的要素以进行正确的排列?

应做如下修改:

permutation(X,X).

permutation(L,[T|Q]) :-
   dif(L,[T|Q]),
   select(T,L,L1),
   permutation(L1,Q).

allperm(L,R) :-
    maplist(permutation,L,R).

我们将“身份”排列扩展到任何 Prolog 项(permutation 的第一个子句),并在第二个子句中禁止它(无论如何只能应用于列表)。