Understanding the evaluation of input function arguments

I read Hadley Wickham's Advanced R, which introduces some very good exercises. One of them asks to describe this function:

f1 <- function(x = {y <- 1; 2}, y = 0) { x + y } f1() 

Can someone help me understand why it returns 3? I know that something is called lazy evaluation of input arguments and, for example, another exercise requires a description of this function

 f2 <- function(x = z) { z <- 100 x } f2() 

and I correctly predicted that it is 100; x gets the value of z , which is calculated inside the function, and then x is returned. However, I cannot understand what is happening in f1() .

Thanks.

+7
r lazy-evaluation
source share
1 answer

See this from https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Evaluation :

When a function is called or called, a new evaluation frame is created. In this frame, the formal arguments are mapped to the given arguments in accordance with the rules given in the argument mappings. Operators in the body of a function are evaluated sequentially in this environment .... R takes the form of a lazy evaluation of function arguments. Arguments are not evaluated until needed.

and this is from https://cran.r-project.org/doc/manuals/r-patched/R-lang.html#Arguments :

The default values ​​for the 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 called by the expression, it will be associated with the corresponding character. When a value is needed, the expression is evaluated in the function evaluation frame.

Thus, if the parameter does not have a user-defined value, its default value will be evaluated in the function evaluation frame. Therefore, y not evaluated first. When the default value x is evaluated in the function evaluation frame, y will be changed to 1, then x will be set to 2. Since y has already been found, the default argument has no changes evaluated. if you try f1(y = 1) and f1(y = 2) , the results are still 3 .

+7
source share

All Articles