I’m using: SWI-Prolog Multi-threaded, 64 bits, Version 7.2.3
I want the code to:
find all possible permutations of the given list. It must run select2() function for different possible values of H, thereby giving the different permutations. However each time by base case is fixed and therefore for empty list ([]) it must always return empty list.
But what I’m getting is:
When I am running the Prolog Program , first time it gives the list itself which is correct, then when I try to find other possible permutations by using ‘;’ operator, for finding other alternatives, it tries to run the rule for the base case instead of the fact. I understand that maybe thats what ‘;’ does. However my requirement is to run the fact always for base case and every time the only variations should result from the select2() function whose output decides the working of the following permutation() function
My code looks like this:
permutation([],[]).
permutation(L,[H|T]):-
select2(H,L,R),
permutation(R,T).
select2(_,[],[]).
select2(X,[X|T],T):-!.
select2(X,[H|T],[H|L]):-
select2(X,T,L).
My trace looks like this
?- trace,permutation([3,2,1],L).
Call: (8) permutation([3, 2, 1], _G1620) ? creep
Call: (9) select2(_G1738, [3, 2, 1], _G1750) ? creep
Exit: (9) select2(3, [3, 2, 1], [2, 1]) ? creep
Call: (9) permutation([2, 1], _G1739) ? creep
Call: (10) select2(_G1741, [2, 1], _G1753) ? creep
Exit: (10) select2(2, [2, 1], [1]) ? creep
Call: (10) permutation([1], _G1742) ? creep
Call: (11) select2(_G1744, [1], _G1756) ? creep
Exit: (11) select2(1, [1], []) ? creep
Call: (11) permutation([], _G1745) ? creep
Exit: (11) permutation([], []) ? creep
Exit: (10) permutation([1], [1]) ? creep
Exit: (9) permutation([2, 1], [2, 1]) ? creep
Exit: (8) permutation([3, 2, 1], [3, 2, 1]) ? creep
L = [3, 2, 1] ;
Redo: (11) permutation([], _G1745) ? creep
Call: (12) select2(_G1747, [], _G1759) ? creep
Exit: (12) select2(_G1747, [], []) ? creep
Call: (12) permutation([], _G1748) ? creep
Exit: (12) permutation([], []) ? creep
Exit: (11) permutation([], [_G1747]) ? creep
Exit: (10) permutation([1], [1, _G1747]) ? creep
Exit: (9) permutation([2, 1], [2, 1, _G1747]) ?
…
This is a part of the trace. As can be clearly seen, from the alternative output case, it goes into a computation which is yielding the results I want([2,1,_G1747]).
I am a beginner here so please pardon any mistakes