如何在 Kotlin 中使用 foldRight()?

teh*_*log 2 kotlin

我试试这个代码

        println(listOf(1, 2, 4).foldRight(0) { total, next ->
            total - next
        })
Run Code Online (Sandbox Code Playgroud)

我认为它像 0 + 4 - 2 - 1 = 1 一样工作。但它返回 3。为什么?对不起这个愚蠢的问题。

gpe*_*che 9

foldRight 通过从右到左累加结果来工作。在你的情况下,它会做

(1 - (2 - (4 - 0))) = (1 - (2 - 4)) = 1 - (-2) = 3

请注意,您的操作的参数顺序错误,foldRight 会将下一个元素作为第一个参数传递给您,将累加器作为第二个参数传递给您。请参阅https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold-right.html。如果你交换它们,你会有

(((0 - 4) - 2) - 1) = - 7

除非我做错了什么