r-lib / coro

Coroutines for R
https://coro.r-lib.org/
Other
156 stars 7 forks source link

Yield in nested iterators #31

Closed dfalbel closed 3 years ago

dfalbel commented 3 years ago

Is the following behaviour expected? I am trying to yield while iterating over a generator. Something like this, where 1:10 could be any iterator created with as_iterator().

library(coro)

g <- coro::generator(function() {
  coro::iterate(for (x in 1:10) {
    if (x < 5)
      yield(x)
    else
      yield(-1)
  })
})

g <- g()
g()
#> Error: `yield()` can't be called directly or within function arguments

Created on 2020-11-16 by the reprex package (v0.3.0)

lionel- commented 3 years ago

We should improve the error message. You don't need iterate() within generators, all for loops are instrumented so they support iterator functions.