loop()
and collect()
are helpers for iterating over
iterator functions such as generators.
loop()
takes afor
loop expression in which the collection can be an iterator function.collect()
loops over the iterator and collects the values in a list.
Value
collect()
returns a list of values; loop()
returns
the exhausted()
sentinel, invisibly.
See also
async_collect()
for async generators.
Examples
generate_abc <- generator(function() for (x in letters[1:3]) yield(x))
abc <- generate_abc()
# Collect 1 element:
collect(abc, n = 1)
#> [[1]]
#> [1] "a"
#>
# Collect all remaining elements:
collect(abc)
#> list()
# With exhausted iterators collect() returns an empty list:
collect(abc)
#> list()
# With loop() you can use `for` loops with iterators:
abc <- generate_abc()
loop(for (x in abc) print(x))
#> [1] "a"
#> [1] "b"
#> [1] "c"