Skip to contents

it <- iteror(obj, ...) is a generic constructor that creates objects of class "iteror" from its input. An iteror outputs a single element of a sequence each time you call nextOr(it). Different iteror methods exist for different data types and may take different optional arguments as listed in this page.

Usage

iteror(obj, ...)

# S3 method for iter
iteror(obj, ...)

# S3 method for default
iteror(obj, ..., recycle = FALSE, chunkSize, chunks)

# S3 method for connection
iteror(obj, ...)

Arguments

obj

An object to iterate with.

...

Different iteror methods may take additional options depending on the class of obj.

recycle

a boolean describing whether the iterator should reset after running through all its values.

chunkSize

How many elements (or slices) to include in each chunk.

chunks

Split the input into this many chunks.

Value

an object of classes 'iteror' and 'iter'.

The method iteror.iter wraps an iterators::iter object and returns an iteror.

The default method iteror.default treats obj as a vector to yield values from.

Details

When called, an iteror may either return a new value or stop. The way an iteror signals a stop is that it does whatever you write in the argument or. For instance you can write or=break to exit a loop. Summing over an iteror this way looks like:

sum <- 0
it <- iteror(iseq(0, 100, 7))
repeat {
  sum <- sum + nextOr(it, break)
}

Another way to use the "or" argument is to give it a sentinel value; that is, a special value that you will interpret as end of iteration. If the result of calling nextOr is identical() to the value you provided, then you know the iterator has ended. This pattern looks like:

sum <- 0
stopped <- new.env()
it <- iteror(iseq(0, 100, 7))
repeat {
  val <- nextOr(it, stopped)
  if (identical(val, stopped)) break
  sum <- sum + val
}

(Here I'm using new.env() as a sentinel value. In R it is commonplace to use NULL or NA as a kind of sentinel value, but that only works until you have an iterator that needs to yield NULL itself. A safer alternative is to use a local, one-shot sentinel value; new.env() is ideal, as it constructs an object that is not identical to any other object in the R session.)

Note that iteror objects are simply functions with a class attribute attached, and all nextOr.iteror does is call the function. So if you were in the mood, you could skip calling nextOr involving S3 dispatch and instead call the iteror directly. If you take this approach, make sure you have called iteror() first to ensure that you have a true iteror object.

sum <- 0
it <- iteror(iseq(0, 100, 7))
repeat sum <- sum + it(or=break)
sum
#> [1] 735

To create iterors with custom-defined behavior, see iteror.function.

See also

iteror.array iteror.function iteror.data.frame