counter <- function(low, high, step) {
current <- low
function() {
if (current > high) {
return(NULL)
}
result <- current
current <<- current + step
result
}
}
# One value per call, made on demand
next_number <- counter(3, 9, 2)
repeat {
number <- next_number()
if (is.null(number)) break
cat("number =", number, "\n")
}
# No end condition: it never finishes by itself
powers_of_two <- function() {
current <- 1
function() {
result <- current
current <<- current * 2
result
}
}
# replicate() asks for exactly five
next_power <- powers_of_two()
first_five <- replicate(5, next_power())
# first_five = 1 2 4 8 16
cat("first_five =", first_five, "\n")