简单迭代器

数组和集合 / 迭代器

new_counter <- function(low, high, step) {
  current <- low
  list(
    has_next = function() current <= high,
    next_value = function() {
      result <- current
      current <<- current + step
      result
    }
  )
}

counter <- new_counter(3, 9, 2)
while (counter$has_next()) {
  number <- counter$next_value()
  cat("number =", number, "\n")
}

# The counter is used up
is_done <- !counter$has_next()
cat("is_done =", is_done, "\n")
# is_done = TRUE