r - When is Lexical Scope for a function within a function determined? -
i've looked @ other lexical scoping questions in r , can't find answer. consider code:
f <- function(x) { g <- function(y) { y + z } z <- 4 x + g(x) } f(3)
f(3)
return answer of 10. question why? @ point g()
defined in code, z
has not been assigned value. @ point closure g()
created? "look ahead" rest of function body? created when g(x)
evaluated? if so, why?
when f
run, first thing happens function g
created in f
's local environment. next, variable z
created assignment.
finally, x
added result of g(x)
, returned. @ point g(x)
called, x = 3
, g
exists in f
's local environment. when free variable z
encountered while executing g(x)
, r looks in next environment up, calling environment, f
's local environment. finds z
there , proceeds, returning 7. adds x
3.
(since answer attracting more attention, should add language bit loose when talking x
"equals" @ various points not accurately reflect r's delayed evaluation of arguments. x
will be equal 3 once value needed.)
Comments
Post a Comment