【问题标题】:recursive function building in RR中的递归函数构建
【发布时间】:2013-08-12 16:57:04
【问题描述】:

如何在 R 中转换该伪代码,以使所有绑定都冻结在定义函数时的状态?

lastfunction <- function(inputx) {rep(0,length(inputx))}
i<-1
while(i<=2){
  afunction <- function(inputx) {i*inputx} #freeze all variable used in the body
  lastfunction <- lastfunction + afunction #and of course the label "afunction" as well
  i<-i+1
}

#then apply to some data
lastfunction(c(0,1,5,6))

我查看了环境,但看不到如何正确设置(嵌套环境?)

【问题讨论】:

  • 你能用看起来不像 R 的东西重写你的伪代码吗?您正在添加两个函数,但我不明白您的意思。
  • 只是在尾注上:看看?Recall

标签: r recursion functional-programming


【解决方案1】:

您可以使用local 创建和使用新环境。

f <- list()
for(i in 1:10) {
  f[[i]] <- local({
      j <- i  # j is only visible in this local environment, 
              # and it is a different environment at each iteration.
      function() j
  })
}
f[[3]]()
# [1] 3

也可以用(function(){ ... })() 代替local

instead of `local({ ... })`.
f <- list()
for(i in 1:10) {
  f[[i]] <- 
    (function(){
      j <- i
      function() j
    })()
}
f[[3]]()

你的例子变成:

f <- function(x) rep(0, length(x))
for(i in -1:2) {
  f <- local({
    # Copy the variables i and f 
    j  <- i
    g1 <- f
    g2 <- function(x) j*x
    # Define the new function
    function(x) {
      cat( "i=", j, " Adding ", paste0(g2(x),sep=","), "\n", sep="" )
      g1(x) + g2(x)
    }
  })
}

# Check that result is correct
h <- function(x) 2*x
f(1:3)
# i=2 Adding 2,4,6,
# i=1 Adding 1,2,3,
# i=0 Adding 0,0,0,
# i=-1 Adding -1,-2,-3,
# [1] 2 4 6
h(1:3)
# [1] 2 4 6

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 2020-11-05
    • 1970-01-01
    • 2013-04-21
    • 2018-08-28
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多