How does R know not to use the old "f"?

In console R, type:

#First code snippet
x <- 0
x <- x+1
x

You will get a "1". This makes sense: the idea is that the “x” in “x + 1” is the current value of x, namely 0, and this is used to calculate the value x + 1, namely 1, which is then dragged into the container x. So far so good.

Now enter:

#Second code snippet
f <- function(n) {n^2}
f <- function(n) {if (n >= 1) {n*f(n-1)} else {1}}
f(5)

You will get "120", which is 5 factorials.

I find this perplexing. Following the logic of the first code snippet, we can expect the “f” in the expression

if (n >= 1) {n*f(n-1)} else {1}

to be interpreted as the current value of f, namely

function(n) {n^2}

Following this argument, the value of f (5) should be 5 * (5-1) ^ 2 = 80. But this is not what we get.

Question. What's going on here? How does R know not to use the old "f"?

+4
2

, 'f'

if (n >= 1) {n*f(n-1)} else {1}

f

- , . .

" f"? , , ""?

"" - , . f(5) . , , , f, (= ) , .

: , , , . , , , .

. , f , :

n = 5
f = function() n ^ 2

n = 1
f() # = 1

, , , (.. "" f).

, : , . twice - , . , , :

twice = function (original_function) {
    force(original_function)
    function (...) {
        original_function(original_function(...))
    }
}

, twice, :

plus1 = function (n) n + 1
plus2 = twice(plus1)
plus2(3) # = 5

Neat-R , !

f:

f = function(n) {n^2}
f = twice(f)
f(5) # 625

... : f = twice(f) f (= ) . f .

+12

, Konrad :

a <- 2
f <- function() a*b

e <- new.env()
assign("b",5,e)
environment(f) <- e

> f()
[1] 10

b <- 10

> f()
[1] 10

, f, e b. , ?lockBinding, , .

, , , , e , f. f, f , , e .

+3

All Articles