Jan Bodnar
Jan Bodnar

Reputation: 11637

Kotlin reduce how to apply operation on more than one element

I have a list of numbers. I want to have the following operation: 1*2 + 3*4. However, the reduce operation works only with one element at a time. And in my case I need to work with two elements at a time. Is it possible to do this with reduce, or with any other method?

package com.zetcode

fun main(args: Array<String>) {

    val nums = listOf(1, 2, 3, 4)

    val res = nums.reduce { total, next -> total * next }
    println(res)
}

Upvotes: 1

Views: 1482

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

You need list.chunked(2) to turn your list into a list of two-member lists and then fold instead of reduce to produce the result (because the type of the result is no longer the same as the type of the list items):

val nums = listOf(1, 2, 3, 4)
val res = nums
        .chunked(2)
        .fold(0) { total, next -> total + next[0] * next[1] }
println(res)

It's mostly stylistic choice, but I prefer to avoid heavyweight fold functions and instead break down the computation into smaller steps, like this:

val res = nums
        .chunked(2)
        .map { it.reduce(Int::times) }
        .sum()

If you're after performance, having less steps is better due to less intermediate lists created. On the other hand, if you're after performance, you should use lazy sequences to begin with, and then the price of each step is much lower.

Upvotes: 6

Related Questions