iteror.function {iterors} | R Documentation |
Construct an iteror object with custom-programmed behavior.
Description
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 class ''function''
iteror(obj, ..., catch, sentinel, count)
Arguments
obj |
A function. It should have having an argument named "or" |
... |
Undocumented. |
catch |
If |
sentinel |
If |
count |
If |
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.
Value
An object of mode "function" and class "iteror".
An iteror which calls the given function to produce values.
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")
# an endless random number generator
irand <- function(min, max) {
iteror(function() runif(1, min=min, max=max), count=Inf)
}
take(irand(5, 10), 10)