gpt4 book ai didi

kotlin - 如何在 Kotlin 中使用 foldRight()?

转载 作者:行者123 更新时间:2023-12-01 15:43:29 24 4
gpt4 key购买 nike

我试试这个代码

        println(listOf(1, 2, 4).foldRight(0) { total, next ->
total - next
})

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

最佳答案

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

除非我出了什么问题

关于kotlin - 如何在 Kotlin 中使用 foldRight()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47013801/

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