Đra*_*nus 8 prolog iso-prolog prolog-cut
我有这个跟踪元解释器,从以前的问题Prolog unbind绑定变量改变.
我不明白如何解释切.感谢用户@false告诉我切割工作很糟糕,我的问题是,我应该如何在这个元解释器中实现切割?
%tracer
mi_trace(Goal):-
mi_trace(Goal, 0).
mi_trace(V, _):-
var(V), !, throw(error(instantiation_error, _)).
mi_trace(true, _Depth):-!, true.
mi_trace(fail, _Depth):-!, fail.
mi_trace(A > B, _Depth):-!, A > B.
mi_trace(A < B, _Depth):-!, A < B.
mi_trace(A =< B, _Depth):-!, A =< B.
mi_trace(A >= B, _Depth):-!, A >= B.
mi_trace(A = B, _Depth):-!, A = B.
mi_trace(A is B, _Depth):-!, A is B.
mi_trace(\+A, _Depth):-!, \+mi_trace(A, _Depth).
mi_trace(!, _Depth):-!, fail. % <- this is wrong
mi_trace((Goal1, Goal2), Depth):-
!,
mi_trace(Goal1, Depth),
mi_trace(Goal2, Depth).
mi_trace(Goal, Depth):-
display('Call: ', Goal, Depth),
redo_clause(Depth, Goal, Body),
Depth1 is Depth + 1,
mi_trace(Body, Depth1),
display('Exit: ', Goal, Depth).
mi_trace(Goal, Depth):-
display('Fail: ', Goal, Depth),
fail.
redo_clause(Depth, Goal, Body) :-
findall(Goal-Body, clause(Goal, Body), [First|Rest]),
( Goal-Body = First
; length(Rest, RL), length(RestC, RL),
member(Goal-Body,RestC),
display('Redo: ', Goal, Depth),
Rest = RestC
).
display(Message, Goal, Depth):-
tab(Depth), write(Depth), write(': '), write(Message),
write(Goal), nl.
trace_query(In, Out, Query):-
consult(In),
tell(Out),
call_with_depth_limit(findall(Query, mi_trace(Query), _Solutions), 30, _XMessage),
writeln(_XMessage),
writeln(_Solutions),
told,
unload_file(In),
true.
Run Code Online (Sandbox Code Playgroud)
让我从一个适用于许多程序的简单实现开始,但不是全部.
catch/3
和throw/1
这种方法绝对是在ISO Prolog中实现切割的最简单方法.但是,效率不高.基本的想法是,cut只是成功,只有在回溯时它才会失败直到最后一次调用mi_call/1
.请注意,只有mi_call/1
构造才能捕获这些削减.因此,所有用户定义的目标都必须包含在内mi_call/1
.因此内置插件相同setof/3
.
一个天真的实现是:
mi_cut.
mi_cut :- throw(cut).
mi_call(Goal) :-
catch(Goal, cut, fail).
Run Code Online (Sandbox Code Playgroud)
在您的元解释器中,将两个规则交换为:
mi_trace(!, _Depth):-!, ( true ; throw(cut) ).
...
mi_trace(Goal, Depth):-
display('Call: ', Goal, Depth),
Depth1 is Depth + 1,
catch(
( redo_clause(Depth, Goal, Body),
mi_trace(Body, Depth1)
),
cut,
fail),
display('Exit: ', Goal, Depth).
Run Code Online (Sandbox Code Playgroud)
这几乎适用于所有程序.除了那些,那是throw(cut)
他们自己.或者想要捕获所有异常.正是这些小小的东西使得一般实现变得更加复杂.
在你的示踪剂,你还没有实现call/1
,catch/3
,throw/1
就目前而言,等等这些问题不会出现-你只是得到一个错误的那些.(也许是TBC)