Hadley's "Advanced R" book contains the following example that I have a hard time understanding.
add <- function(x) { function(y) x + y } adders <- lapply(1:10, add) adders[[1]](10) #> [1] 20 adders[[10]](10) #> [1] 20
x is lazily evaluated the first time that you call one of the adder functions. At this point, the loop is complete and the final value of x is 10. Therefore all of the adder functions will add 10 on to their input, probably not what you wanted!
I check and it is indeed true that x
within each adders[[num]]
evaluates to 10
.
get("x", envir=environment(adders[[2]])) # = 10
get("x", envir=environment(adders[[9]])) # = 10
But why? For example, when adders[[2]]
is defined as the returned value of add(2)
, at that moment x = 2
. According to Hadley, "a function preserves the environment in which it was defined." So why didn't adders[[2]]
preserve the environment in which x = 2
?