R中的发电机功能

pap*_*rin 21 python r generator python-3.x

R中是否有一个包或语言结构可以促进或提供" 类似Python的生成器 "的实现?

通过"类似Python的生成器",我指的是在调用之间保持状态的函数,在R语法中,从Python 借用关键字yield将类似于:

iterable.fun <- function(){
  yield list('a','b','c')
}
Run Code Online (Sandbox Code Playgroud)

使用yield而不是return,然后连续三次调用函数将给出:

> iterable.fun()
  'a'
> iterable.fun()
  'b'
> iterable.fun()
  'c'
Run Code Online (Sandbox Code Playgroud)

编辑:我遗漏了Python生成器的一个方面,使它们与迭代器不同.迭代的整个对象列表不是在第一次调用时构建的,然后是迭代的,但是每个函数调用都会创建一个将为该调用返回的元素.

mne*_*nel 24

iterators软件包具有此功能

library(iterators)
abc <- iter(c('a','b','c'))
nextElem(abc)
## [1] "a"
nextElem(abc)
## [1] "b"
nextElem(abc)
## [1] "c"
Run Code Online (Sandbox Code Playgroud)

或者你可以使用lambda.r<<-.此示例已修改

http://cartesianfaith.wordpress.com/2013/01/05/infinite-generators-in-r/

博客文章中有更多的例子

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
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以使用常规函数来执行此操作.

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
Run Code Online (Sandbox Code Playgroud)

如果要从可能的列表中进行选择,则可以使用 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"
Run Code Online (Sandbox Code Playgroud)


kra*_*ski 6

coro该团队最新的包(协程)r-lib提供了生成器、迭代器和自适应生成器。生成器的行为完全符合人们的预期(文档中的复制粘贴示例):

library(coro)

generate_abc <- generator(function() {
  for (x in letters[1:3]) {
    yield(x)
  }
})
# Create the iterator
abc <- generate_abc()

# Use the iterator by invoking it
abc()
#> [1] "a"

abc()
#> [1] "b"

# Last value
abc()
#> [1] "c"

# Exhaustion sentinel
abc()
#> exhausted

abc()
#> exhausted
Run Code Online (Sandbox Code Playgroud)

查看更多信息https://github.com/r-lib/coro