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

时间:2014-10-20 21:37:06

标签: recursion prolog interpreter trace

我有这个跟踪元解释器,我在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。

1 个答案:

答案 0 :(得分:2)

您添加了几个内置谓词,例如(>)/2

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

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

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

另外,请注意,您收到了很多关于void变量的警告:使用_删除案例。