This package is an attempt at an implementation of a "Pythonesque" generator data type and methods. It didn't work out 100% ... there's no magic yield
method :( ... but I figured I'd share it anyways, in case anyone might find it useful.
See here for more information on Python generators.
Install from github with:
# install.packages("devtools")
devtools::install_github("ChrisMuir/generatr")
library(generatr)
Initialize a new generator
object with an R vector
gen <- gen_init_with_vector(c(1L, 5L, 20L, 45L))
Check the class of the object gen
class(gen)
#> [1] "integer" "generator" "externalptr"
Use gen_next()
to get the next value from a generator
object, similar to Python's __next__()
for (i in 1:4) {
print(gen_next(gen))
}
#> [1] 1
#> [1] 5
#> [1] 20
#> [1] 45
Use gen_current()
to get the current value from a generator
object
gen_current(gen)
#> [1] 45
Once all values have been exhausted, gen_next()
will throw a StopIteration
error
gen_next(gen)
#> Error in C_gen_next(gen, type_in): StopIteration
We can also initialize a new generator
object as an empty object
gen <- gen_init_empty(gen_type = "integer")
Again, check the class of object gen
class(gen)
#> [1] "integer" "generator" "externalptr"
New items can be added one by one
for (i in c(1L, 5L, 20L, 45L)) {
gen_add_element(gen, i)
}
Once we're finished adding items, gen_next()
and gen_current()
work just like they did in the previous example
for (i in 1:4) {
print(gen_next(gen))
}
#> [1] 1
#> [1] 5
#> [1] 20
#> [1] 45
Currently, the only data types supported are integer
, numeric
, character
, and logical
gen <- gen_init_with_vector(c("cats", "dogs", "ducks", "frogs", "owls"))
for (i in 1:5) {
print(gen_next(gen))
}
#> [1] "cats"
#> [1] "dogs"
#> [1] "ducks"
#> [1] "frogs"
#> [1] "owls"