Search code examples
kotlinfunctional-programmingfold

Fold that returns intermediate results and not just the last one


I'm looking for a function similar to fold, which doesn't return only the final result but all intermediate results as well.

For example with fold I could implement the following example:

val res = listOf(1,2,3).fold(0, { acc, it -> f(acc, it) })
// res = 6

But I'm looking for something like...

val res = listOf(1,2,3).foo(0, { acc, it -> f(acc, it) })
// res = listOf(1,3,6)

...which then would return the intermediate results instead of just the final sum.

Is there something like this foo function already included in Kotlins stdlib or what would be a common name for this foo in functional programming style?


Solution

  • Not sure if this exists in kotlin, but that's called scan. You could see this answer for more details (not kotlin, but, since Scala influenced it a lot, probably you even wont see syntax differences).