Implementing a Lazy Generator
Explore how to implement lazy generators in Go by using goroutines and channels. Understand the concept of lazy evaluation to generate sequences on demand, saving resources. Learn to build generic lazy evaluators with higher-order functions and channels, enabling efficient and concurrent data production with controlled resource use.
We'll cover the following...
Introduction
A generator is a function that returns the next value in a sequence each time the function is called, like:
generateInteger() => 0
generateInteger() => 1
generateInteger() => 2
....
It is a producer that only returns the next value, not the entire sequence. This is called _lazy evaluations, which means only computing what you need at the moment, therefore saving valuable resources (memory and CPU). It is technology for the evaluation of expressions on demand.
Explanation
An example (of lazy generation) would be the generation of an endless sequence of even numbers. To generate it and use those numbers one by one would be difficult and certainly would not fit into memory! But, a simple function per type with a channel and a goroutine can do the job.
For example, in the following program, we see a Go implementation with a channel of a generator of ints. The channel is named yield and resume, terms commonly used in coroutine code.
In the code above, at line 6, resume is declared as a channel of integers. This is initialized at line 24, where it gets the return value of the integers() function. ...