了解函数输入参数的评估 [英] Understanding evaluation of input arguments of functions

查看:74
本文介绍了了解函数输入参数的评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读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.

谢谢.

推荐答案

请参见

当调用或调用一个函数时,会出现一个新的求值框架 创建.在这个框架中,形式论证与 根据参数匹配中给出的规则提供参数. 函数主体中的语句按顺序求值 在这种环境下. ... R具有函数参数的惰性求值形式.直到需要时才会评估参数.

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.

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.

这篇关于了解函数输入参数的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆