Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is Lexical Scope for a function within a function determined?

I've looked at the other lexical scoping questions in R and I can't 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 an answer of 10. My question is why? At the point g() is defined in the code, z has not been assigned any value. At what point is the closure for g() created? Does it "look ahead" to the rest of the function body? Is it created when the g(x) is evaluated? If so, why?

like image 428
Steve Rowe Avatar asked Apr 14 '15 17:04

Steve Rowe


People also ask

What is needed for lexical scoping?

In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the current scope chain.

How is lexical scoping implemented?

To get correct lexical scoping and closures in an interpreter, all you need to do is follow these rules: In your interpreter, variables are always looked up in an environment table passed in by the caller or kept as a variable, not some global env-stack.

What is the scope inside a function called?

A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.

How can we define the scope of a function?

So the "scope of a function" could mean two things: either the scope defined by the function's body, in which its local variables are declared; or the scope (either a class or a namespace) in which the function name is declared.


1 Answers

When f is run, the first thing that happens is that a function g is created in f's local environment. Next, the variable z is created by assignment.

Finally, x is added to the result of g(x) and returned. At the point that g(x) is called, x = 3 and g exists in f's local environment. When the free variable z is encountered while executing g(x), R looks in the next environment up, the calling environment, which is f's local environment. It finds z there and proceeds, returning 7. It then adds this to x which is 3.

(Since this answer is attracting more attention, I should add that my language was a bit loose when talking about what x "equals" at various points that probably do not accurately reflect R's delayed evaluation of arguments. x will be equal to 3 once the value is needed.)

like image 70
joran Avatar answered Sep 28 '22 02:09

joran