R 中的词法作用域和 <<- 运算符
Lexical scoping and the <<- operator in R
此代码出现在 Intro to R 手册中。
open.account <- function(total) {
list(deposit = function(amount) {
if (amount <= 0) stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
}, withdraw = function(amount) {
if (amount > total) stop("You don’t have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
}, balance = function() {
cat("Your balance is", total, "\n\n")
})
}
这应该模拟银行账户的运作方式,在计算存款和取款时跟踪 运行 余额。为此,程序需要查看每笔交易前的余额,这是动态的,因此不能用函数定义。这是我有点模糊的地方...
我的问题专门针对 <<-
运算符,它允许函数在环境之外索引 total
的值。
词法范围规则规定变量或对象的值在它们被定义的环境中确定。这决定了 where r 应该看,而不是 when。
也就是说,当我们使用<<-
运算符指向当前环境之外的值时,指向哪里呢?这是一个概念性问题,使我无法完全掌握它的工作原理。我了解代码的工作原理,但我不确定当我们使用 <<-
运算符时从哪里提取值。
The operators ‘<<-’ and ‘->>’ are normally only used in functions,
and cause a search to made through parent environments for an
existing definition of the variable being assigned. If such a
variable is found (and its binding is not locked) then its value
is redefined, otherwise assignment takes place in the global
environment
全局变量
z <- 10
不修改z的全局值
myfun <- function(x){
z <- x
print(z)
}
修改 myfun 中 z
的值,但不要在全局级别修改 z。
myfun0 <- function(x){
z <- x
myfun1 <- function(y){
z <<- (y+1)
}
myfun1(x)
print(z)
}
修改全局环境中的z
myfunG <- function(x){
z <<- x
print(" z in the global envronment is modified")
}
另见 this post。
此代码出现在 Intro to R 手册中。
open.account <- function(total) {
list(deposit = function(amount) {
if (amount <= 0) stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
}, withdraw = function(amount) {
if (amount > total) stop("You don’t have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
}, balance = function() {
cat("Your balance is", total, "\n\n")
})
}
这应该模拟银行账户的运作方式,在计算存款和取款时跟踪 运行 余额。为此,程序需要查看每笔交易前的余额,这是动态的,因此不能用函数定义。这是我有点模糊的地方...
我的问题专门针对 <<-
运算符,它允许函数在环境之外索引 total
的值。
词法范围规则规定变量或对象的值在它们被定义的环境中确定。这决定了 where r 应该看,而不是 when。
也就是说,当我们使用<<-
运算符指向当前环境之外的值时,指向哪里呢?这是一个概念性问题,使我无法完全掌握它的工作原理。我了解代码的工作原理,但我不确定当我们使用 <<-
运算符时从哪里提取值。
The operators ‘<<-’ and ‘->>’ are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment
全局变量
z <- 10
不修改z的全局值
myfun <- function(x){
z <- x
print(z)
}
修改 myfun 中 z
的值,但不要在全局级别修改 z。
myfun0 <- function(x){
z <- x
myfun1 <- function(y){
z <<- (y+1)
}
myfun1(x)
print(z)
}
修改全局环境中的z
myfunG <- function(x){
z <<- x
print(" z in the global envronment is modified")
}
另见 this post。