R - for 循环可能有错误,而它使用的 acc 是一个函数。但为什么呢?

问题描述 投票:0回答:1

问题

有这样的案例

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"

和 while 循环有同样的问题...

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 语言中的什么原因造成了这个问题?

我在 R-4.3.3webr REPL 中对此进行了测试。一个简单的演示可以在这里找到。

r loops for-loop while-loop currying
1个回答
0
投票

正如罗兰所说,这归因于懒惰的评估。您可以使用

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"
© www.soinside.com 2019 - 2024. All rights reserved.