Could someone please explain why the following snippet behaves as it does?
l <- list()
AddFn <- function(str) { l[[length(l) + 1]] <<- function() { return(str) }}
AddFn("hello")
AddFn("there")
l[[1]]() # Returns "hello" as expected
l[[2]]() # Returns "there" as expected
for (letter in letters) AddFn(letter)
l[[3]]() # Returns "z"
I expected l[[3]]() to return “a”. What am I missing? What exactly does my AddFn function do?
Thank you in advance,
Adrian
Lazy evaluation often results in the last evaluation in a loop getting returned. Try this instead: