首页 > 解决方案 > 如何在重复中累积(永远)

问题描述

在硬件设备的命令和控制的上下文中,我需要一个无限循环“获取-详细-发布”并记住当前状态,以观察输入的演变,例如“变为”真实的布尔值。

我编写了一个模型,下面的程序,它产生了一个奇怪的行为(对我来说),我很惊讶,因为我Previous没有失败地设置有界变量,为什么?

Previous我希望出现类似“变量已绑定”之类的错误消息,但不,回溯是为了解决约束(很多次!)。

#!/usr/bin/swipl

init( Previous, AtStart ) :-
    get_time( AtStart ),
    Previous is 0.

run( AtStart, Previous ) :- % I want this to be executed only once for each period!
    get_time( Now ),
    Elapsed is Now - AtStart,
    Current is Previous + random( 20 ),
    format( "~w: Previous = ~w~n", [Elapsed, Previous] ),
    format( "~w: Current  = ~w~n", [Elapsed, Current ] ),
    Previous is Current.

periodicTask :-
    init( Previous, AtStart ),
    repeat,
        run( AtStart, Previous ),
        sleep( 1.0 ).

:-
    periodicTask.

它以这种输出无限期运行:

?- periodicTask.
?- periodicTask.
0.0231266: Previous = 0
0.0231266: Current  = 10
0.243902: Previous = 0
0.243902: Current  = 16
............................ A lot of lines
0.934601: Previous = 0
0.934601: Current  = 0
true ;
2693.8: Previous = 0
2693.8: Current  = 19
............................ A lot of lines
2694.65: Previous = 0
2694.65: Current  = 0
 true ;
3694.98: Previous = 0
3694.98: Current  = 2
............................ A lot of lines
3695.17: Previous = 0
3695.17: Current  = 0
 true ;
4695.47: Previous = 0
4695.47: Current  = 10
............................ A lot of lines
4695.55: Previous = 0
4695.55: Current  = 0
true 
  1. 为什么?

  2. 如何编写一个无限循环来重置(解除绑定)一些变量并保留全局上下文?

“递归”的答案在这里似乎不适用,不是吗?

标签: prologinfinite-loop

解决方案


这是一个用尾递归调用编写的简单循环,它将激活 T 处的“状态”传输到激活 T + 1 处的“状态”,非常自然(正如哥德尔在每个人都想出来并开始使用forwhile ):

periodicTask :-
    get_time(AtStart),
    run(AtStart,0).        

stopCriteriumFulfilled :- fail. % TO BE DONE

run(AtStart,Previous) :-
    !,                       % Possibly optional: drop open chociepoints in infinite loop                       
    get_time(Now),
    Elapsed is Now - AtStart,
    Current is Previous + random( 20 ),
    format( "~w: Previous = ~w~n", [Elapsed, Previous] ),
    format( "~w: Current  = ~w~n", [Elapsed, Current ] ),
    % 
    % Now call yourself with a new context in which the 
    % variable "Current" ("here", in this activation)
    % becomes the variable "Previous" ("there", in the next activation)
    % But first sleep a bit (N.B. numbers are numbers, one can use 1 
    % instead of 1.0)
    % One may want to add a stop criterium here to succeed the predicate
    % instead of performing the tail-recursive call unconditionally.
    % 
    (stopCriteriumFulfilled
     -> true
      ; (sleep(1),
         run(AtStart,Current))). % RECURSIVE TAIL CALL
 
:- periodicTask.

如果需要比将当前状态传递给下一次激活更多的“状态性”,请查看以下内容:


推荐阅读