简体   繁体   English

在这个使用 reduce() 内部迭代器 function 的示例中,为什么累加器不确认这个数字?

[英]In this example using the reduce() internal iterator function, why won't the accumulator acknowledge this digit?

I'm kind of baffled here.我在这里有点困惑。 I'm simply trying to use the reduce function to create a String representing the elements of a list in numbered order.我只是想使用 reduce function 来创建一个字符串,该字符串按编号顺序表示列表的元素。 Here is the code:这是代码:

val names = listOf("John", "Billy", "Tom", "Joe", "Eric", "Jerry") 

val result = names.reduce { accum, name -> "$accum ${names.indexOf(name) + 1}. $name" }

println(result)     // John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry

                   // ^ missing 1.  

I'm expecting the value of the accumulator to accumulate as such after each iteration:我期望累加器的值在每次迭代后这样累加:

"1. John" “1.约翰”

"1. John 2. Billy" “1. 约翰 2. 比利”

"1. John 2. Billy 3. Tom" “1. 约翰 2. 比利 3. 汤姆”

"1. John 2. Billy 3. Tom 4. Joe" “1. 约翰 2. 比利 3. 汤姆 4. 乔”

"1. John 2. Billy 3. Tom 4. Joe 5. Eric" “1. 约翰 2. 比利 3. 汤姆 4. 乔 5. 埃里克”

"1. John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry" “1. 约翰 2. 比利 3. 汤姆 4. 乔 5. 埃里克 6. 杰瑞”

When I run the code, it prints: John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry当我运行代码时,它会打印:John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry

I don't understand why the "1."我不明白为什么是“1”。 is missing,不见了,

Reduce function uses your first value as a starting accumulator.减少 function 使用您的第一个值作为起始累加器。

So operation is only applied between (((1 -> 2) -> 3) -> 4) pairs.所以操作只适用于(((1 -> 2) -> 3) -> 4)对之间。

You can achieve expected behaviour with fold function, which takes initial value:您可以使用折叠function 实现预期的行为,它采用初始值:

val result = names.fold("") { accum, name -> "$accum ${names.indexOf(name) + 1}. $name" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM