counter <- function(low, high, step) {
current <- low
function() {
if (current > high) {
return(NULL)
}
result <- current
current <<- current + step
result
}
}
# По одному значению за вызов, создаётся по требованию
next_number <- counter(3, 9, 2)
repeat {
number <- next_number()
if (is.null(number)) break
cat("number =", number, "\n")
}
# Условия окончания нет: сам он никогда не завершится
powers_of_two <- function() {
current <- 1
function() {
result <- current
current <<- current * 2
result
}
}
# replicate() запрашивает ровно пять
next_power <- powers_of_two()
first_five <- replicate(5, next_power())
# first_five = 1 2 4 8 16
cat("first_five =", first_five, "\n")