我正在尝试callto_status(Goal, Status)
根据调用的结果定义一个始终成功并统一 Status的关系Goal
(换句话说,我想实现一个具体化的版本call_with_inference_limit/3
)。call_with_inference_limit/3
我的实现使用具有相同接口的SWI call_with_time_limit/3
(在这种情况下也应该可以工作)。的实施call_with_..._limit
不会回溯,所以我认为最好不要给人以报告答案替代目标的印象。
我介绍了辅助谓词derivable_st
以提高可读性。它处理成功和超时情况,否则失败。
% if Goal succeeds, succeed with Status = true,
% if Goal times out, succeed with Status = timeout
% if Goal fails, fail
derivable_st(Goal, Status) :-
T = 10000, % set inference limit
% copy_term(Goal, G), % work on a copy of Goal, we don't want to report an answer substitution
call_with_inference_limit(G, T, R), % actual call to set inference limit
( R == !
-> Status = true % succeed deterministically, status = true
; R == true
-> Status = true % succeed non-deterministically, status = true
; ( R == inference_limit_exceeded % timeout
-> (
!, % make sure we do not backtrack after timeout
Status = timeout % status = timeout
)
; throw(unhandled_case) % this should never happen
)
).
主要谓词环绕derivable_st
并处理失败情况和可能抛出的异常(如果有的话)。我们可能想要找出堆栈溢出(在推理限制太高的情况下发生),但现在我们只报告任何异常。
% if Goal succeeds, succeed with Status = true,
% if Goal times out, succeed with Status = timeout
% if Goal fails, succeed with Status = false
% if Goal throws an error, succeed with Status = exception(The_Exception)
% Goal must be sufficiently instantiated for call(Goal) but will stay unchanged
callto_status(Goal, Status) :-
catch(( derivable_st(Goal, S) % try to derive Goal
-> Status = S % in case of success / timeout, pass status on
; Status = false % in case of failure, pass failure status on, but succeed
),
Exception,
Status = exception(Exception) % wrap the exception into a status term
).
谓词适用于一些简单的测试用例:
?- callto_reif( length(N,X), Status).
Status = true.
?- callto_reif( false, Status).
Status = false.
?- callto_reif( (length(N,X), false), Status).
Status = timeout.
我现在的问题有点含糊:这个谓词是否像我声称的那样做?您是否看到任何错误/改进点?我很感激任何意见!
编辑:正如@false 所建议的,注释掉了copy_term/2