When is a Lexic Scope for a function within a specific function?

I looked at other lexical questions in R and I can not find the answer. Consider this code:

f <- function(x) { g <- function(y) { y + z } z <- 4 x + g(x) } f(3) 

f(3) will return the answer 10. My question is: why? At the point g() is defined in the code, z not been assigned any value. At what point is the closure created for g() ? Does he "look to the future" at the rest of the body functions? Is g(x) created in the estimation? If so, why?

+8
r lexical-scope
source share
1 answer

When f is executed, the first thing that happens is that in f local environment creates a function g . Then the variable z is created by assignment.

Finally, x added to the result of g(x) and returned. At a point called g(x) , x = 3 and g exists in the local environment f . When a free variable z is encountered at runtime g(x) , R looks up into the next environment, causing the environment, which is the local environment f . He finds z there and continues, returning 7. Then he adds this to x , which is 3.

(Since this answer attracts more attention, I should add that my language was a little loose when I said that x β€œequal” at different points, which probably do not accurately reflect R, the delayed evaluation of the arguments. x will be 3, when it is necessary.)

+10
source share

All Articles