prolog - 如何在重复中累积(永远)
问题描述
在硬件设备的命令和控制的上下文中,我需要一个无限循环“获取-详细-发布”并记住当前状态,以观察输入的演变,例如“变为”真实的布尔值。
我编写了一个模型,下面的程序,它产生了一个奇怪的行为(对我来说),我很惊讶,因为我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
为什么?
如何编写一个无限循环来重置(解除绑定)一些变量并保留全局上下文?
“递归”的答案在这里似乎不适用,不是吗?
解决方案
这是一个用尾递归调用编写的简单循环,它将激活 T 处的“状态”传输到激活 T + 1 处的“状态”,非常自然(正如哥德尔在每个人都想出来并开始使用for和while ):
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.
如果需要比将当前状态传递给下一次激活更多的“状态性”,请查看以下内容:
推荐阅读
- sas - 在满足某些要求时保持观察
- spring-boot - 即使 DB 已关闭,也启动 Spring-Boot/EclipseLink 应用程序,并在 DB 可用时重新连接
- android - 未找到 Google 插件服务,添加时已存在
- python - 在熊猫中“拆分”行的正确方法
- r - 如何使 xlab 与其在 R 中的表示(条形图)一致
- java - 将字符串(名称)添加到单独的实例
- sql - 将格式为 35:23:12 的 VARCHAR 转换为我可以求和的数据类型
- c++ - 如何在不同的文件头上添加班级朋友?
- amazon-web-services - 使用 lambda 从外部 s3 存储桶下载文件
- c++ - 相同的 AVX2 程序在 gcc 和 msvc 中产生不同的结果