Iterator protocol
An iterator is a function that implements the following protocol:
Calling the function advances the iterator. The new value is returned.
When the iterator is exhausted and there are no more elements to
return, the symbol quote(exhausted)
is returned. This signals
exhaustion to the caller.
Once an iterator has signalled exhaustion, all subsequent
invokations must consistently return quote(exhausted)
.
iterator <- as_iterator(1:3) # Calling the iterator advances it iterator()
## [1] 1
iterator()
## [1] 2
# This is the last value iterator()
## [1] 3
# Subsequent invokations return the exhaustion sentinel iterator()
## exhausted
Because iteration is defined by a protocol, creating iterators is
free of dependency. However, it is often simpler to create
iterators with generators, see
vignette("generator")
. To loop over an iterator, it is simpler
to use the loop()
and collect()
helpers provided in this
package.
exhausted() is_exhausted(x)
x |
An object. |
Iterators are stateful. Advancing the iterator creates a persistent effect in the R session. Also iterators are one-way. Once you have advanced an iterator, there is no going back and once it is exhausted, it stays exhausted.
Iterators are not necessarily finite. They can also represent infinite sequences, in which case trying to exhaust them is a programming error that causes an infinite loop.
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.