Menu
Coddy logo textTech

Pattern Iterator

Fa parte della sezione Programmazione orientata agli oggetti del percorso R di Coddy. Lezione 49 di 57.

Un iteratore fornisce gli elementi di una collezione uno alla volta, così il codice che li usa non deve sapere come è memorizzata la collezione. Una chiusura mantiene la posizione; has_next() e next_value() costituiscono l’intera interfaccia:

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 

Un generatore è un iteratore che calcola ogni valore quando viene richiesto, quindi la sequenza non deve esistere in memoria. Può essere persino infinito:

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 

L'iteratore nasconde la struttura. I risultati memorizzati in pagine, alcune delle quali vuote, vengono restituiti come un'unica sequenza piatta:

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 

Gli helper scritti per l’interfaccia funzionano con ogni iteratore. take(it, n) recupera fino a n valori da un vettore, un generatore o qualsiasi altra cosa dotata di has_next() e 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

Sfida

Facile

Completa Iterator.R:

  • make_iterator(x): un iteratore sugli elementi di un vettore, con has_next() e next_value();
  • make_range(from, to, by): un generatore di from, from + by, ... fino a to incluso, calcolati uno alla volta;
  • take(it, n): fino a n valori successivi di un iteratore qualsiasi.

Il codice fornito legge righe range 1 10 3 take 2 5 (from, to, by, poi le dimensioni di ogni take) oppure list a,b,c take 2 2, e stampa ciò che restituisce ogni take().

Il tuo codice va in Iterator.R. main.R contiene il codice di input/output fornito e non può essere modificato.

Provalo tu

source("Iterator.R")

# Codice di input/output fornito: lascialo così com'è
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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Programmazione orientata agli oggetti

Esercitati da solo: Compilatore R online