https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Steven Wang

09/11/2020, 5:20 PM
how to perform cumProd() operation over a list?
n

nanodeath

09/11/2020, 5:22 PM
list.forEach { it.foo() }
s

Shawn

09/11/2020, 5:25 PM
I don’t think that’s what they mean by `cumProd()`…
s

Steven Wang

09/11/2020, 5:25 PM
hmm not sure, how it can do cumulative multiplication ?
s

Shawn

09/11/2020, 5:25 PM
assuming you mean cumulative product, then you probably want something like this
Copy code
list.runningReduce { acc, next -> acc * next }
n

nanodeath

09/11/2020, 5:26 PM
depends also whether you want a single value at the end -- if yes, probably fold/reduce
s

Shawn

09/11/2020, 5:26 PM
if you’re working with a numeric type, you can shorten that by providing a reference to its
times
method, for example with `Int`:
Copy code
val cumprod = ints.runningReduce(Int::times)
1
s

Steven Wang

09/11/2020, 5:27 PM
got it, thx, that's exactly I wanted.
👍 1
5 Views