0

According to lazy evaluation in R (Advanced R by H. Wickham P.85), the following code should return 20, however I get the return equal to 11. Did I misunderstand anything?

add <- function(x) {

function(y) x + y

}

adders <- lapply(1:10, add)
adders[[1]](10)
demongolem
  • 9,474
  • 36
  • 90
  • 105
  • 2
    You misread the book. `adders[[1]](10)` is expected to return 11 ([book](http://adv-r.had.co.nz/Functions.html#function-arguments)), whereas `adders[[10]](10)` is expected to return 20. More detail: Expanding the `lapply` statement, adders[[1]]` is the same as `add(1)`, which returns `function(y) y + 1`. You're then calling that function with `y = 10`, so the result is `10 + 1 = 11`. – Alexey Shiklomanov Apr 17 '17 at 13:50
  • I believe you want to read this. http://stackoverflow.com/questions/16129902/explain-a-lazy-evaluation-quirk – PKumar Apr 17 '17 at 16:03

0 Answers0