Permute into a list SWI-Prolog

后端 未结 2 631
感动是毒
感动是毒 2020-12-21 01:41

How do you use the permute predicate to output into a list in SWI prolog?

The permutation/2 predicate only returns one result at a time.

2条回答
  •  不知归路
    2020-12-21 02:33

    The most straight forward way to describe all permutations is using bagof/3. Note that findall/3 cannot be used directly, since findall produces literal copies of the original list.

    list_allperms(L, Ps) :-
       bagof(P, permutation(L,P), Ps).
    
    ?- L = [A,B,C], list_allperms(L, Ps).
    L = [A, B, C],
    Ps = [[A, B, C], [A, C, B], [B, A, C], [B, C, A], [C, A, B], [C, B, A]].
    

    So that's the no-brainer version. But you can even implement it directly in pure Prolog without any auxiliary built-ins.

提交回复
热议问题