递归 – Prolog跟踪解释器在执行递归程序时无法进入无限循环

我有这个跟踪元解释器,我在Ivan Bratko编写的书中找到了Prolog Programming For Artifical Intelligence第3版,它看起来像这样:

trace(Goal):-
    trace(Goal, 0).

trace(true, Depth):-!.
%I added those below because I want to allow numeric operations
trace(A > B, Depth):-!.
trace(A < B, Depth):-!.
trace(A = B, Depth):-!.
trace(A is B, Depth):-!.
trace((Goal1, Goal2), Depth):-!,
    trace(Goal1, Depth),
    trace(Goal2, Depth).
trace(Goal, Depth):-
    display('Call: ', Goal, Depth),
    clause(Goal, Body),
    Depth1 is Depth + 1,
    trace(Body, Depth1),
    display('Exit: ', Goal, Depth),
    display_redo(Goal, Depth).
trace(Goal, Depth):-
    display('Fail: ', Goal, Depth),
    fail.

display(Message, Goal, Depth):-
    tab(Depth), write(Message),
    write(Goal), nl.

display_redo(Goal, Depth):-
    true
    ;
    display('Redo: ', Goal, Depth),
    fail.

有人可以解释为什么这个跟踪元解释器无法跟踪像factorial或fibonnaci数这样的递归程序?

我使用SWI-Prolog版本6.6.6.

最佳答案 您添加了几个内置谓词,如(>)/ 2:

trace(A > B, Depth):-!.

但是你提供的解释只是说:它总是如此.因此,您的程序永远不会终止.相反,提供实际解释:

trace(A > B, _Depth) :- !,
   A > B.

另外,请注意您收到很多关于void变量的警告:使用_删除案例就像这样.

点赞