In a context of command and control of a hardware device, I need an infinite loop "acquire-elaborate-publish" with a memorization of the current state, to observe evolution of inputs like a boolean which "becomes" true.
I have coded a mockup, the following program, which produce a strange behaviour (for me) and I'm surprised because I set the bounded variable Previous without failure, why?
I expect an error message like 'variable Previous is already bound' but no, backtracking is done to resolve constraints (many times!).
#!/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.
It runs indefinitely with this kind of output:
?- 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
Why?
How to code an infinite loop which reset (unbound) some variables and preserve a global context?
The answer 'by recursion' does not seem applicable here, no?