Friday, May 31, 2024

Lazy sequences

Lazy sequences are a useful tool in programming.  They represent potentially infinite sequences of data, but only one element at a time.  You could represent the natural numbers as a lazy sequence of 0, 1, 2, 3, ...  The trick is to limit how many of these elements you create and use at a time.  Of course, you could also use lazy evaluation of a finite sequence, like iterating through each element of a list, but only as needed by the program logic

How do you create a lazy sequence?

next(state, iterator)

state is the current state of your sequence.  It might be a list and a pointer to the current element, or it might be the current integer in an infinite series.

iterator is a function that, given the state, produces the current element in sequence and updates the state.  If given the state of 5, an iterator should produce 5 and then update the state to 6.  If given a state like [[`a `b `c `d `e `f `g], 2], the iterator should produce `c and then update the 2 to a 3.  In addition, the iterator function must also report whether it has reached the limit of its function as a boolean (true/false) flag.  This could occur by reaching the end of a list, or by iterating all the way to the highest (or lowest) expressible value of the function.

next is simply a function that applies the iterator function to the state.  Ultimately, next produces an iteration result along with a status indicator.  This indicator should be used by the surrounding program loop to decide whether to continue the lazy iteration or not.

No comments:

Post a Comment

I reserve the right to remove egregiously profane or abusive comments, spam, and anything else that really annoys me. Feel free to agree or disagree, but let's keep this reasonably civil.