# NOT RUN {
#Create the Collatz sequence starting with 50 and print out the first 30 elements
collatz <- Iterator({
if (n %% 2 == 0) n <- n / 2 else n <- n*3 + 1
},
initial = c(n = 50),
yield = n)
seq <- yield_more(collatz, 30)
# If you want to define the expression outside the Iterator, use [quote()] and `!!`:
expr <- quote(if (n %% 2 == 0) n <- n / 2 else n <- n*3 + 1)
collatz <- Iterator(!!expr,
c(n = 50),
n)
# using objects defined outside `$initial`:
# Note that `n` in `$initial` overrides the global `n`
m <- 100
n <- 10
it <- Iterator({out <- n + m},
initial = c(n = -10),
yield = out)
yield_next(it)
# environments are modified in place, so be aware:
it <- Iterator({m <- m + 1}, c(m = 0), m)
other <- it
yield_next(it)
current(other)
# }
Run the code above in your browser using DataLab