In console R, type:
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:
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"?