R Language: Lexical vs. Dynamic Scoping

0

Lexical scoping is a concept in programming languages that determines how the values of variables are assigned in a function. In lexical scoping, the values of free variables are searched for in the environment in which the function was defined, not in the environment in which the function is called.

Dynamic scoping is a concept in programming languages that determines how the values of variables are assigned in a function. In dynamic scoping, the values of free variables are searched for in the environment from which the function was called.

The main difference between lexical scoping and dynamic scoping is where the values of free variables are looked up. In lexical scoping, the values of free variables are looked up in the environment in which the function was defined. In dynamic scoping, the values of free variables are looked up in the environment from which the function was called.

Here is an example of lexical scoping:

y <- 10


f <- function(x) {

  y <- 2

  y^2 + g(x)

}


g <- function(x) { 

  x*y

}


f(3)

In this example, the value of `y` in the function `g` is looked up in the environment in which `g` was defined, which is the global environment. The value of `y` in the global environment is 10, so the value of `f(3)` is 140.

Here is an example of dynamic scoping:

y <- 10


f <- function(x) {

  y <- 2

  y^2 + g(x)

}


g <- function(x) { 

  x*y

}


y <- 3

f(3)

In this example, the value of `y` in the function `g` is looked up in the environment from which `g` was called. The environment from which `g` was called is the environment in which `f(3)` was called. The value of `y` in the environment in which `f(3)` was called is 3, so the value of `f(3)` is 27.

Lexical scoping is a more common scoping mechanism than dynamic scoping. R uses lexical scoping.

Post a Comment

0Comments
Post a Comment (0)