Menu
Coddy logo textTech

Iterator Pattern

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 49 of 57.

An iterator hands out the items of a collection one at a time, so the code that uses them does not need to know how the collection is stored. A closure keeps the position; has_next() and next_value() are the whole interface:

make_iterator <- function(x) {
  i <- 0
  list(
    has_next = function() i < length(x),
    next_value = function() {
      i <<- i + 1
      x[[i]]
    }
  )
}
it <- make_iterator(c("a", "b", "c"))
while (it$has_next()) cat(it$next_value(), "")

Output:

a b c 

A generator is an iterator that computes each value when it is asked for, so the sequence does not have to exist in memory. It can even be endless:

make_fib <- function() {
  a <- 0
  b <- 1
  list(has_next = function() TRUE,
       next_value = function() {
         value <- a
         nxt <- a + b
         a <<- b
         b <<- nxt
         value
       })
}
fib <- make_fib()
for (i in 1:10) cat(fib$next_value(), "")

Output:

0 1 1 2 3 5 8 13 21 34 

The iterator hides the layout. Results stored in pages, some of them empty, come out as one flat sequence:

make_paged <- function(pages) {
  p <- 1
  i <- 0
  skip_empty <- function() while (p <= length(pages) && i >= length(pages[[p]])) { p <<- p + 1; i <<- 0 }
  list(
    has_next = function() { skip_empty(); p <= length(pages) },
    next_value = function() { skip_empty(); i <<- i + 1; pages[[p]][i] }
  )
}
it <- make_paged(list(c("a", "b"), character(0), c("c")))
while (it$has_next()) cat(it$next_value(), "")

Output:

a b c 

Helpers written against the interface work with every iterator. take(it, n) pulls up to n values, from a vector, a generator or anything else with has_next() and next_value():

make_iterator <- function(x) {
  i <- 0
  list(has_next = function() i < length(x), next_value = function() { i <<- i + 1; x[[i]] })
}
take <- function(it, n) {
  out <- c()
  while (length(out) < n && it$has_next()) out <- c(out, it$next_value())
  out
}
it <- make_iterator(1:5)
print(take(it, 2))
print(take(it, 10))

Output:

[1] 1 2
[1] 3 4 5
challenge icon

Challenge

Easy

Complete Iterator.R:

  • make_iterator(x): an iterator over the elements of a vector, with has_next() and next_value();
  • make_range(from, to, by): a generator of from, from + by, ... up to and including to, computed one at a time;
  • take(it, n): up to n next values of any iterator.

The supplied code reads lines range 1 10 3 take 2 5 (from, to, by, then the sizes of each take) or list a,b,c take 2 2, and prints what each take() returns.

Your code goes in Iterator.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Iterator.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  it <- if (p[1] == "range") make_range(as.numeric(p[2]), as.numeric(p[3]), as.numeric(p[4])) else make_iterator(strsplit(p[2], ",")[[1]])
  k <- if (p[1] == "range") 5 else 3
  for (n in as.numeric(p[-(1:k)])) {
    got <- take(it, n)
    cat("take ", n, ": ", if (length(got) == 0) "(nothing)" else paste(got, collapse = " "), "\n", sep = "")
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online R compiler