https://kotlinlang.org logo
Title
d

Daniele B

01/29/2021, 5:25 PM
I have a list of MyObj, already sorted by date:
data class MyObj (
    val date : String,
    val dailyAmount : Int,
    val cumulativeAmount : Int,
)
where
cumulativeAmount
is empty I would like to iterate over that list, and populate
cumulativeAmount
with the sum of all
dailyAmount
until that date How to do?
e

ephemient

01/29/2021, 5:28 PM
Kotlin stdlib doesn't have a combination fold+map function, so you'll have to do it yourself
d

Daniele B

01/29/2021, 5:29 PM
ok, so I will just use a standard for loop, which keeps the cumulative amount?
e

ephemient

01/29/2021, 5:29 PM
sure, that would be a good way to do it
you could imagine a generic implementation that looks something like this
to be used like
list.foldMap(0) { acc, element ->
    val cumulativeAmount = acc + element.dailyAmount
    cumulativeAmount to element.copy(cumulativeAmount = cumulativeAmount)
}
n

nanodeath

01/29/2021, 5:37 PM
imperative-style coding isn't the worst -- it pained me but I replaced a functional method with an imperative one yesterday because it was 10x clearer to understand. might be similar here.
☝️ 1
e

ephemient

01/29/2021, 5:43 PM
it depends. if this were a common pattern, then that would be one thing. I've used
mapAccum
in Haskell plenty of times (that would be the closest equivalent function). but I've never needed this function more than once in Kotlin, so I don't think it's really necessary with how Kotlin code is usually written (or at least how my code is written)
t

tseisel

01/30/2021, 9:44 AM
That's a use case for
runningFold
!
list.runningFold(list.first()) { acc, obj ->
    obj.copy(cumulativeAmount = acc.cumulativeAmount + obj.dailyAmount)
}.drop(1)
e

ephemient

01/30/2021, 12:52 PM
different behavior than mine: cumulativeSum doesn't include the element itself, and fails on empty list. whether that matters depends on OP (and is easily addressable), of course