Search code examples
kotlinfunctional-programming

Is there a functional way to map a list (N elements) to a list of sums of adjacent elements (N - 1 elements) in Kotlin?


If it is possible using reduce/fold or other functional ways then I cannot find out how to do that. I need to somehow transform a list of let's say: 1, 2, 5, 2 to 3 (1+2), 7 (2+5), 7 (5+2)

I understand the problem is that reduce/fold iterate over adjacent elements but it is only one of the elements that is used with the result of reducing the previous. If there were a way to iterate over overlapping/intersecting pairs then it would allow for what I need.


Solution

  • What you need is a sliding window of two elements while iterating over the list. You can do it in Kotlin like this:

    val result = listOf(1, 2, 5, 2)
        .windowed(2) {
            it.sum()
        }
    

    result now contains the list [3, 7, 7].