Why doesn't lazy evaluation break this code?

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?

Upvotes: 5

Views: 158

Answers (1)

Erdős-Bacon
Erdős-Bacon

Reputation: 918

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

Upvotes: 9

Related Questions