R中的函数环境

R中的函数环境,r,function,environment,R,Function,Environment,我有以下代码来理解复杂的环境层: depositor <- function() { balance <- 0 function(amount) { balance <<- balance + amount # assign in the parent return(balance) } } deposit <- depositor() deposit(100) 100 deposit(32) 132 depositor理解这个例子的

我有以下代码来理解复杂的环境层:

depositor <- function() {
  balance <- 0
  function(amount) {
   balance <<- balance + amount # assign in the parent
    return(balance) 
  } 
}
deposit <- depositor()
deposit(100)
100
deposit(32)
132

depositor理解这个例子的关键是
depositor()
它会回来的

depositor()

function(amount) {
   balance <<- balance + amount # assign in the parent
    return(balance) 
  }
<environment: 0x8936fb0>

deposit理解这个例子的关键是
depositor()
它会回来的

depositor()

function(amount) {
   balance <<- balance + amount # assign in the parent
    return(balance) 
  }
<environment: 0x8936fb0>

deposit
depositor
返回一个函数。此函数将数字作为输入,并记住并返回迄今为止收到的数字的累计和。这是函数中的一个函数。
depositor()
的返回对象是一个函数,这就是
deposit(100)
工作的原因。我的建议是忽略您发现的源代码,因为这不是“正确的”R方式。另一个有趣的实验是通过
deposit2@RomanLuštrik生成另一个函数当然闭包是正确的R方式。请参阅范围界定演示。
存款人
返回一个函数。此函数将数字作为输入,并记住并返回迄今为止收到的数字的累计和。这是函数中的一个函数。
depositor()
的返回对象是一个函数,这就是
deposit(100)
工作的原因。我的建议是忽略您发现的源代码,因为这不是“正确的”R方式。另一个有趣的实验是通过
deposit2@RomanLuštrik生成另一个函数当然闭包是正确的R方式。请参阅范围界定演示。
deposit<- depositor()
x<- depositor()

#following will have two different values
environment(deposit)
environment(x) 
# and they will work independently
x(100); x(20)
deposit(100);deposit(1000)