From this page:
http://adv-r.had.co.nz/Functions.html#lexical-scoping
I'm confused with the following. My confusion comes from the fact that the first and second codes perform identically for me, and not as suggested in the text. The statement that "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!" isn't something I can reconcile. Any help would be appreciated.
add <- function(x) {
function(y) x + y
}
adders <- lapply(1:10, add)
adders[1][1] 11
adders[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! Manually forcing evaluation fixes the problem:
add <- function(x) {
force(x)
function(y) x + y
}
adders2 <- lapply(1:10, add)
adders2[1][1] 11
adders2[10]
[1] 20