-1

How does one transform that pseudo code in R, such that all binding are freezed at the state they were when the function were defined ?

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))

I looked at environments but can't see how to to it properly (nesting environments ?)

4

1 回答 1

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
于 2013-08-11T07:57:59.583 回答