问题描述
我正在阅读Hadley Wickham的Advanced R,其中提供了一些非常好的练习.其中之一要求对此功能进行描述:
I am reading Advanced R by Hadley Wickham where some very good exercises are provided. One of them asks for description of this function:
f1 <- function(x = {y <- 1; 2}, y = 0) {
x + y
}
f1()
有人可以帮助我理解为什么它返回3吗?我知道有一种叫做输入参数的惰性评估的东西,例如另一个练习要求对此功能进行描述
Can someone help me to understand why it returns 3? I know there is something called lazy evaluation of the input arguments, and e.g. another exercise asks for description of this function
f2 <- function(x = z) {
z <- 100
x
}
f2()
我正确地预测是100; x
获取z
的值,该值在函数内部求值,然后返回x.我无法弄清楚f1()
中会发生什么.
and I correctly predicted to be 100; x
gets value of z
which is evaluated inside a function, and then x is returned. I cannot figure out what happens in f1()
, though.
谢谢.
推荐答案
请参见 https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Evaluation :
,并且来自 https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Arguments :
总而言之,如果参数没有用户指定的值,则将在函数的评估框架中评估其默认值.因此,首先不评估y
.在函数的求值框架中求出默认值x
时,将y
修改为1,然后将x
设置为2.由于已经找到y
,因此默认参数没有变化.评估.如果您尝试f1(y = 1)
和f1(y = 2)
,结果仍然是3
.
In summary, if the parameter does not have user-specified value, its default value will be evaluated in the function's evaluation frame. So y
is not evalulated at first. When the default of x
is evaluated in the function's evaluation frame, y
will be modified to 1, then x
will be set to 2. As y
is already found, the default argument has no change to be evaluated. if you try f1(y = 1)
and f1(y = 2)
, the results are still 3
.
这篇关于了解函数输入参数的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!