The iterators
package has this functionality
library(iterators)
abc <- iter(c('a','b','c'))
nextElem(abc)
## [1] "a"
nextElem(abc)
## [1] "b"
nextElem(abc)
## [1] "c"
Or you could use lambda.r
and <<-
. This example is modified from
http://cartesianfaith.wordpress.com/2013/01/05/infinite-generators-in-r/
there are more examples in the blog post
library(lambda.r)
seq.gen(start) %as% {
value <- start - 1L
function() {
value <<- value + 1L
return(value)
}
}
foo <- seq.gen(1)
foo()
## [1] 1
foo()
## [1] 2
foo()
## [1] 3
note that you could also use a regular function to do this.
seq.gen <-function(start) {
value <- start - 1L
function() {
value <<- value + 1L
return(value)
}
}
foo2 <- seq.gen(1)
foo2()
## [1] 1
foo2()
## [1] 2
foo2()
## [1] 3
If you want to select from a possible list, then you could perhaps do so using switch
seq.char(start) %as% {
value <- start - 1L
function() {
value <<- value + 1L
return(switch(value,'a','b','c'))
}
}
foo.char <- seq.char(1)
foo.char()
## [1] "a"
foo.char()
## [1] "b"
foo.char()
## [1] "c"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…