R 惰性评估- 不工作

R Lazy Evaluation- not working

我玩过高级 R 示例 http://adv-r.had.co.nz/Functions.html 并得到了不同的结果。根据这本书,R 惰性评估是默认的。但对我来说,它似乎已被关闭。为什么会这样,如何解决?

我得到的:

add <- function(x) {
    function(y) x+y
}
adders <- lapply(1:10, add)
adders[[1]](10)
[1] 11    **The book gave 20 instead of 11**
adders[[10]](10)
[1] 20

在 R 3.2.0 中对 R 进行了此更改:

Higher order functions such as the apply functions and Reduce() now force arguments to the functions they apply in order to eliminate undesirable interactions between lazy evaluation and variable capture in closures. This resolves PR#16093.

这可以在以下的 R 3.2.0 部分找到:

https://cran.r-project.org/doc/manuals/r-devel/NEWS.html

另见:

https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16093

使用 R 3.2.0 之前版本的演示

force 添加到问题中的代码将导致 3.2.0 之前的 R 与 3.2.0 一样工作。

使用 R 3.1.3 我们可以通过使用 force 和不使用 force 来显示差异:

R.version.string
## [1] "R version 3.1.3 Patched (2015-03-16 r68169)"

# adding force to the code in the question
# In R 3.2.0 onwards conceptually R acts as if this R 3.1.3 code were run
add <- function(x) {
    force(x)  # <---------------------------
    function(y) x+y
}
adders <- lapply(1:10, add)
adders[[1]](10)
## [1] 11

# not using force, i.e. using identical code as in the question
add <- function(x) {
    function(y) x+y
}
adders <- lapply(1:10, add)
adders[[1]](10)
## [1] 20