Understanding Variable Coverage Functions

For this code:

A <- 100; B <- 20 f1 <- function(a) { B <- 100 f2 <- function(b) { A <<- 200 B <<- 1000 } f2(a) } f1(B) cat(A) cat(B) 

Below is the conclusion:

 > cat(A) 200 > cat(B) 20 

Here is my understanding of the above code: The function f1 is called with parameter B, which has a value of 20. Inside f1, a local variable B is created (B <100), f1.B does not affect the variable B, the initialized external call to the function f1, since f1.B is locally bound to the function f1. In f1, a new function f2 is created that takes a single argument b. Inside f1, the function f2 is called by passing as parameter a to f2. f2 does not use its argument b. f2 modifies A using the global <- operator and sets it to 200. This is why cat (A) prints 200.

My understanding is wrong, since B is set to 20 when I expect 1000? Since the value of A is set to 200 in f2, using <-. d should also not occur for B?

+5
source share
1 answer

Function f1 is called with parameter B, which has a value of 20.

No, I do not think so. It is called with parameter a , which has the same meaning as B in the global environment. B not directly involved at this point.

Then you assign 100 to other B that you call f1.B in your message. (Note that following the previous statement, B is created here, not rewritten.)

Then, using the operator <<- , it crosses the scope, moving from f2 (where there is no B ) to f1 , where it finds it " f1.B " and assigns 1000.

Similarly, when using <<- on a it passes. It does not find a in f2 or f1 , but does it in a global environment and assigns it there.

Then you print to the old original B , which never changed.

Via:

<<- and ->> (...) invokes a search in the parent environments for the existing definition of the variable being assigned. If such a variable is found (and its binding is not blocked), then its value is overridden, otherwise the assignment occurs in the global environment.

So, for B "such a variable is found", and for a "assignment occurs in a global environment."

Conclusion: <<- confusing, and often best avoided.

+5
source

Source: https://habr.com/ru/post/1273915/


All Articles