gpt4 book ai didi

prolog - 具体化 call_with_time_limit/call_with_inference_limit

转载 作者:行者123 更新时间:2023-12-04 12:50:34 27 4
gpt4 key购买 nike

我正在尝试定义关系 callto_status(Goal, Status)总是成功,根据调用Goal的结果统一Status (换句话说,我想实现 call_with_inference_limit/3 的具体版本)。我的实现使用 SWI 的 call_with_inference_limit/3call_with_time_limit/3 具有相同的接口(interface)(这应该使它在这种情况下也能工作)。 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

最佳答案

这是一个较短的解决方案:

callto_status(Goal, Status) :-
call_with_inference_limit(Goal, 10000, Status0),
(Status0 = ! -> !, Status = true; Status = Status0).
callto_status(_, false).

你看看原来的用处有多大! status是避免不必要的选择点:
?- callto_status(member(X,[1,2,3]), Y).
X = 1,
Y = true
X = 2,
Y = true
X = 3,
Y = true.

?- callto_status(fail, Y).
Y = false.

您当然也可以替换 Status0 = ! -> !, Status = true通过 Status0 = ! -> Status = true只要。然后,您将始终获得剩余的选择点:
?- callto_status(member(X,[1,2,3]), Y).
X = 1,
Y = true
X = 2,
Y = true
X = 3,
Y = true
Y = false.

从问题中不清楚你到底想要什么。

关于prolog - 具体化 call_with_time_limit/call_with_inference_limit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54678295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com