有这样的案例
acc = \ (a) \ (b) base::list(a = a, b = b)
for (x in c("A","B")) {acc = acc(x)}
acc
返回:
$a
[1] "B"
$b
[1] "B"
但应该是一样的,
acc = \ (a) \ (b) base::list(a = a, b = b)
# for (x in c("A","B")) {acc = acc(x)}
acc = acc("A")
acc = acc("B")
acc
意味着它应该返回:
$a
[1] "A"
$b
[1] "B"
acc = \ (x) \ (y) \ (z) base::list(x = x, y = y, z = z)
for (i in c("A","B","C")) {acc = acc(i)}
acc
返回:
$x
[1] "C"
$y
[1] "C"
$z
[1] "C"
但应该与
相同acc = \ (x) \ (y) \ (z) base::list(x = x, y = y, z = z)
# for (i in c("A","B","C")) {acc = acc(i)}
acc = acc("A")
acc = acc("B")
acc = acc("C")
acc
意味着它应该返回:
$x
[1] "A"
$y
[1] "B"
$z
[1] "C"
acc = \ (a) \ (b) base::list(a = a, b = b)
.iter = c("A","B")
.i = 0
while (.i < length(.iter)) {acc <<- acc <- acc(.iter[.i + 1]); .i = .i + 1}
print(acc)
R 语言中的什么原因造成了这个问题?
正如罗兰所说,这归因于懒惰的评估。您可以使用
force
来绕过它:
acc = \ (a) {force(a); \ (b) base::list(a = a, b = b)}
for(i in c("A", "B")) { acc <- acc(i) }
acc
#> $a
#> [1] "A"
#>
#> $b
#> [1] "B"
和
acc <- function (x) {
force(x)
function (y) {
force(y)
function (z) {
base::list(x = x, y = y, z = z)
}
}
}
for (i in c("A","B","C")) { acc = acc(i) }
acc
#> $x
#> [1] "A"
#>
#> $y
#> [1] "B"
#>
#> $z
#> [1] "C"