R中的递归函数构建

时间:2013-08-11 05:29:23

标签: r recursion functional-programming

如何在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))

我查看了环境,但看不到如何正确处理它(嵌套环境?)

1 个答案:

答案 0 :(得分:2)

您可以使用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