R中的生成器功能 [英] Generator functions in R

查看:365
本文介绍了R中的生成器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R中是否有一个软件包或语言构造可促进或提供"类似Python的生成器?

Is there a package or language construct in R that facilitates or provides the implementation of "Python-like generators"?

通过类似于Python的生成器",我的意思是保持调用之间状态的函数(使用R语法)并从Python借用关键字 yield 类似于:

By "Python-like generators" I mean functions that keep state between calls, in R syntax and borrowing the keyword yield from Python will be something like:

iterable.fun <- function(){
  yield list('a','b','c')
}

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

With yield instead of a return, then calling the function three consecutive times would give:

> iterable.fun()
  'a'
> iterable.fun()
  'b'
> iterable.fun()
  'c'

我忽略了Python生成器的一个方面,使它们与迭代器不同.只是要迭代的对象的整个列表不是在第一个调用上构建的,而是在迭代后构建的,但是每个函数调用都会创建一个元素,该元素将为该调用返回.

I left out an aspect of Python generators that makes them different from iterators. It is that the whole list of objects to iterate on is not built on the first call and then iterated, but each function call creates the one element that will return for that call.

推荐答案

iterators软件包具有此功能

library(iterators)
abc <- iter(c('a','b','c'))
nextElem(abc)
## [1] "a"
nextElem(abc)
## [1] "b"
nextElem(abc)
## [1] "c"

或者您可以使用lambda.r<<-.这个例子是从

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

如果要从可能的列表中进行选择,则可以使用switch

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"

这篇关于R中的生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆