Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Big Cat Public Safety Act Avatar asked Oct 03 '18 16:10

Big Cat Public Safety Act


1 Answers

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

like image 172
Erdős-Bacon Avatar answered Oct 21 '22 03:10

Erdős-Bacon