add <- function(x) {
function(y) x + y
}
adders <- lapply(1:10, add)
adders[[1]](10)
In the above code Wickham claims in Advanced R that because function arguments are lazily evaluated x will be 10 for all of the closures that are created by lapply(1:10, add). But that is not the case after I ran the code in an R session, but even his examples do no demonstrate the breaking of the above code as far as I can tell - why is this?
One of the comments already answered the question: lapply
was modified to have a different behavior than what Wickham wrote at that time.
If you want to dive into it more, here is the R development email thread where it was changed: https://stat.ethz.ch/pipermail/r-devel/2015-February/070686.html
And here is Hadley Wickham discussing how the example will be fixed in the next version of Advanced R: https://github.com/hadley/adv-r/issues/803
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With