Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

iterator

Iterator protocol


Description

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.

Usage

exhausted()

is_exhausted(x)

Arguments

x

An object.

Properties

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.


coro

'Coroutines' for R

v1.0.1
MIT + file LICENSE
Authors
Lionel Henry [aut, cre], RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.