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" }