Skip to contents

Pass obj a function that has a first argument named "or". In writing this function, you can maintain state by using enclosed variables and update using <<-, Whatever value obj() returns is the next element of the iteror. Treat argument or as a lazy value; do not touch it until until you need to signal end of iteration; to signal end of iteration, force and immediately return or.

Usage

# S3 method for `function`
iteror(obj, ..., catch, sentinel, count)

Arguments

obj

A function. It should have having an argument named "or"

...

Undocumented.

catch

If obj does not have an or argument, specify e.g. catch="StopIteration" to interpret that an error with that message as end of iteration.

sentinel

If obj does not have an or argument, you can specify a special value to watch for end of iteration. Stop will be signaled if the function result is identical() to sentinel.

count

If obj does not have an or argument, you can specify how many calls before stop iteration, or give NA or Inf to never stop.

Value

An object of mode "function" and class "iteror".

An iteror which calls the given function to produce values.

Details

You can also provide obj a simple function of no arguments, as long as you specify one of catch, sentinel, or count to specify how to detect end of iteration.

Examples


# an iterator that counts from start to stop
irange <- function(from=1, to=Inf) {
  current <- from
  iteror(function(or) {
    if (current > to) {
      return(or)
    } else {
      tmp <- current
      current <<- current + 1
      tmp
    }
  })
}
it <- irange(5, 10)
as.vector(it, "numeric")
#> [1]  5  6  7  8  9 10

# an endless random number generator
irand <- function(min, max) {
 iteror(function() runif(1, min=min, max=max), count=Inf)
}
take(irand(5, 10), 10)
#> [[1]]
#> [1] 6.224605
#> 
#> [[2]]
#> [1] 5.43818
#> 
#> [[3]]
#> [1] 6.955542
#> 
#> [[4]]
#> [1] 5.912807
#> 
#> [[5]]
#> [1] 5.668124
#> 
#> [[6]]
#> [1] 6.287315
#> 
#> [[7]]
#> [1] 7.766235
#> 
#> [[8]]
#> [1] 5.740346
#> 
#> [[9]]
#> [1] 9.814484
#> 
#> [[10]]
#> [1] 9.722614
#>