了解函数输入参数的评估
Understanding evaluation of input arguments of functions
我正在阅读 Hadley Wickham 的 Advanced R,其中提供了一些非常好的练习。其中一位要求描述此功能:
f1 <- function(x = {y <- 1; 2}, y = 0) {
x + y
}
f1()
谁能帮我理解为什么 returns 3?我知道有一种叫做对输入参数进行惰性评估的东西,例如另一个练习要求描述这个函数
f2 <- function(x = z) {
z <- 100
x
}
f2()
并且我正确预测为 100; x
获取函数内部计算的 z
的值,然后返回 x。不过,我无法弄清楚 f1()
中发生了什么。
谢谢。
从https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Evaluation看到这个:
When a function is called or invoked a new evaluation frame is
created. In this frame the formal arguments are matched with the
supplied arguments according to the rules given in Argument matching.
The statements in the body of the function are evaluated sequentially
in this environment frame.
...
R has a form of lazy evaluation of function arguments. Arguments are not evaluated until needed.
这来自 https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Arguments:
Default values for arguments can be specified using the special form
‘name = expression’. In this case, if the user does not specify a
value for the argument when the function is invoked the expression
will be associated with the corresponding symbol. When a value is
needed the expression is evaluated in the evaluation frame of the
function.
综上所述,如果参数没有用户指定的值,其默认值将在函数的评估框架中评估。所以 y
一开始不会被计算。当在函数的求值框中求值默认的x
时,y
会被修改为1,然后x
会被设置为2。因为y
已经找到了,默认参数没有要评估的变化。如果您尝试 f1(y = 1)
和 f1(y = 2)
,结果仍然是 3
。
我正在阅读 Hadley Wickham 的 Advanced R,其中提供了一些非常好的练习。其中一位要求描述此功能:
f1 <- function(x = {y <- 1; 2}, y = 0) {
x + y
}
f1()
谁能帮我理解为什么 returns 3?我知道有一种叫做对输入参数进行惰性评估的东西,例如另一个练习要求描述这个函数
f2 <- function(x = z) {
z <- 100
x
}
f2()
并且我正确预测为 100; x
获取函数内部计算的 z
的值,然后返回 x。不过,我无法弄清楚 f1()
中发生了什么。
谢谢。
从https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Evaluation看到这个:
When a function is called or invoked a new evaluation frame is created. In this frame the formal arguments are matched with the supplied arguments according to the rules given in Argument matching. The statements in the body of the function are evaluated sequentially in this environment frame. ... R has a form of lazy evaluation of function arguments. Arguments are not evaluated until needed.
这来自 https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Arguments:
Default values for arguments can be specified using the special form ‘name = expression’. In this case, if the user does not specify a value for the argument when the function is invoked the expression will be associated with the corresponding symbol. When a value is needed the expression is evaluated in the evaluation frame of the function.
综上所述,如果参数没有用户指定的值,其默认值将在函数的评估框架中评估。所以 y
一开始不会被计算。当在函数的求值框中求值默认的x
时,y
会被修改为1,然后x
会被设置为2。因为y
已经找到了,默认参数没有要评估的变化。如果您尝试 f1(y = 1)
和 f1(y = 2)
,结果仍然是 3
。