我想限制prolog中算法的"执行"。你能给我一个提示吗,怎么做?我发现了这个谓词:call_with_time_limit如何捕获time_limit_exceeded异常?感谢
更新:
我是这样尝试的:
timeout(t) :-
catch(call_with_time_limit(t, sleep(5)), X, error_process(X)).
error_process(time_limit_exceeded) :- write('Timeout exceeded'), nl, halt.
error_process(X) :- write('Unknown Error' : X), nl, halt.
但注意到当我调用timeout(1(时发生了什么:
prolog :-
timeout(1),
但是当我这样做的时候:
runStart :- call_with_time_limit(1, sleep(5)).
timeout(1) :-
catch(runStart, X, error_process(X)).
error_process(time_limit_exceeded) :- write('Timeout exceeded'), nl, halt.
error_process(X) :- write('Unknown Error' : X), nl, halt.
再次呼叫超时(1(一切正常。为什么?谢谢更新2:
问题解决了,有必要用大写字母预先定义"论点"。。。
使用catch/3
。示例:
catch(call_with_time_limit(1,
sleep(5)),
time_limit_exceeded,
writeln('overslept!')).
更实际:
catch(call_with_time_limit(T, heavy_computation(X)),
time_limit_exceeded,
X = no_answer). % or just fail
loop :- loop.
loop_for_n_sec(N, Catcher) :-
catch(
call_with_time_limit(N, loop),
Catcher,
true
).
用法:
?- loop_for_n_sec(1, Catcher).
Catcher = time_limit_exceeded