Reputation: 71
This is a predicate that get permutations of a list. Can somebody explain to me how to trace this predicate? I am using SWI.
perm([H|T],L) :- perm(T,P) , insert(H,P,L).
perm([],[]).
insert(X,L,[X|L]).
insert(X,[H|T],[H|T1]) :- insert(X,T,T1).
Upvotes: 1
Views: 2055
Reputation: 58244
Here's an example of using trace
in SWI Prolog.
Entering the code:
?- [user].
|: perm([H|T],L) :- perm(T,P) , insert(H,P,L).
|: perm([],[]).
|:
|: insert(X,L,[X|L]).
|: insert(X,[H|T],[H|T1]) :- insert(X,T,T1).
|: % user://1 compiled 0.01 sec, 6 clauses
true.
Running a trace. Press "Enter" at the question marks ?
to "creep" (take a step):
?- trace.
true.
[trace] ?- perm([1,2,3], L).
Call: (6) perm([1, 2, 3], _G366) ? creep
Call: (7) perm([2, 3], _G445) ? creep
Call: (8) perm([3], _G445) ? creep
Call: (9) perm([], _G445) ? creep
Exit: (9) perm([], []) ? creep
Call: (9) insert(3, [], _G446) ? creep
Exit: (9) insert(3, [], [3]) ? creep
Exit: (8) perm([3], [3]) ? creep
Call: (8) insert(2, [3], _G449) ? creep
Exit: (8) insert(2, [3], [2, 3]) ? creep
Exit: (7) perm([2, 3], [2, 3]) ? creep
Call: (7) insert(1, [2, 3], _G366) ? creep
Exit: (7) insert(1, [2, 3], [1, 2, 3]) ? creep
Exit: (6) perm([1, 2, 3], [1, 2, 3]) ? creep
L = [1, 2, 3]
As you might expect, this trace shows that perm
calls itself recursively until it gets to the empty tail ([]
) of the input list [1,2,3]
. It then shows calls to insert
which follow those recursive calls, along with the arguments occurring in those calls. The _Gnnn
variables are uninstantiated arguments on a Call
that gets instantiated in the clause which you see on the Exit
.
Upvotes: 2