gpt4 book ai didi

r - 解释一下惰性评估的怪癖

转载 作者:行者123 更新时间:2023-12-03 05:40:55 24 4
gpt4 key购买 nike

我正在 Github 上阅读 Hadley Wickhams 的书,特别是 this part on lazy evaluation 。在那里,他在 add/adders 函数部分给出了惰性求值后果的示例。让我引用一下那句话:

This [lazy evaluation] is important when creating closures with lapply or a loop:

add <- function(x) {
function(y) x + y
}
adders <- lapply(1:10, add)
adders[[1]](10)
adders[[10]](10)

x is lazily evaluated the first time that you call one of the adder functions. At this point, the loop is complete and the final value of x is 10. Therefore all of the adder functions will add 10 on to their input, probably not what you wanted! Manually forcing evaluation fixes the problem:

add <- function(x) {
force(x)
function(y) x + y
}
adders2 <- lapply(1:10, add)
adders2[[1]](10)
adders2[[10]](10)

我似乎不太明白这一点,而且解释也很少。有人可以详细说明这个特定的例子,并解释那里发生了什么吗?我对“此时,循环已完成,x的最终值为10”这句话感到特别困惑。什么循环?最终值是多少,在哪里?一定是我缺少的简单的东西,但我只是没有看到它。预先非常感谢。

最佳答案

从 R 3.2.0 开始,这不再是事实!

change log中对应的行内容如下:

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.

确实:

add <- function(x) {
function(y) x + y
}
adders <- lapply(1:10, add)
adders[[1]](10)
# [1] 11
adders[[10]](10)
# [1] 20

关于r - 解释一下惰性评估的怪癖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com