Prolog computes permutation

I am writing a permutation function [a, b] β†’ [[[a], [b]], [[a, b]]

I still have it, but it does not work.

perm([],[]). perm(L,[H|T]) :- append(V,[H|U],L), append(V,U,W), perm(W,T). 
+4
source share
3 answers

Given your example, it looks like you might really need a powerset , not a permutation of this list.

For example, the force set [a,b] is the set { [a,b] , [a] , [b] , [] }.

To compute a list of list parameters in Prolog, check out this answer from @gusbro. If this helps you, please also support this answer.

If you want all the solutions to force the set of L lists at once, you can associate the powerset/2 call with the findall/3 call as follows:

 ?- findall(S, powerset(L, S), Ss). 

If, on the other hand, you are after sections (as already mentioned in one of your previous changes), consider the following:

 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 partition/2 predicate accepts a list and returns all partitions as you described. For instance:

 ?- partition([a,b,c],L). L = [[a, b, c]] ; L = [[a, b], [c]] ; L = [[a], [b, c]] ; L = [[a], [b], [c]] ; false. 
+5
source

Really? It works in SWI-Prolog:

 ?- [user]. |: perm([],[]). |: perm(L,[H|T]) :- append(V,[H|U],L), append(V,U,W), perm(W,T). |: % user://1 compiled 0.00 sec, 3 clauses true. ?- perm([a,b,c], X). X = [a, b, c] ; X = [a, c, b] ; X = [b, a, c] ; X = [b, c, a] ; X = [c, a, b] ; X = [c, b, a] ; false. ?- perm([a,b,c,d], X). X = [a, b, c, d] ; /* trimming 22 solutions */ X = [d, c, b, a] ; false. 

It also gives the number of answers you expect: 3! = 6, 4! = 24. What doesn't work for you?

+3
source

Quick note: Prolog does not offer features, but relationships.

In this case, perm / 2 will be true if the arguments are a permutation of the other.

I find this definition more understandable than yours.

 perm([], []). perm([E|Es], P) :- perm(Es, Q), select(E, P, Q). 

This is almost the same as permutation / 2 SWI-Prolog, but hides the error ...

+2
source

Source: https://habr.com/ru/post/1438976/


All Articles