2014-03-28 69 views
0

這是一個謂詞,可以獲得列表的排列。有人可以向我解釋如何追蹤這個謂詞嗎?我正在使用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). 
+1

您是否嘗試在Prolog提示符處鍵入'trace.',然後執行查詢? – lurker

回答

0

下面是在SWI Prolog中使用trace的示例。

輸入代碼:

?- [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. 

運行跟蹤。按「Enter」的問號?爲「爬行」(退一步):

?- 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] 

正如您所料,此跟蹤顯示perm遞歸調用自己,直到它到達的空尾([])輸入列表[1,2,3]。然後它會顯示跟隨這些遞歸調用的insert的調用,以及這些調用中發生的參數。 _Gnnn變量是Call上的無實證參數,它們在您看到的Exit中的子句中得到實例化。

+0

非常感謝:)) – user3423255