简体   繁体   中英

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. 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. John 2. Billy"

"1. John 2. Billy 3. Tom"

"1. John 2. Billy 3. Tom 4. Joe"

"1. John 2. Billy 3. Tom 4. Joe 5. Eric"

"1. John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry"

When I run the code, it prints: John 2. Billy 3. Tom 4. Joe 5. Eric 6. Jerry

I don't understand why the "1." is missing,

Reduce function uses your first value as a starting accumulator.

So operation is only applied between (((1 -> 2) -> 3) -> 4) pairs.

You can achieve expected behaviour with fold function, which takes initial value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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