I have a list of MyObj, already sorted by date: ``...
# getting-started
d
I have a list of MyObj, already sorted by date:
Copy code
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
Kotlin stdlib doesn't have a combination fold+map function, so you'll have to do it yourself
d
ok, so I will just use a standard for loop, which keeps the cumulative amount?
e
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
Copy code
list.foldMap(0) { acc, element ->
    val cumulativeAmount = acc + element.dailyAmount
    cumulativeAmount to element.copy(cumulativeAmount = cumulativeAmount)
}
n
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
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
That's a use case for
runningFold
!
Copy code
list.runningFold(list.first()) { acc, obj ->
    obj.copy(cumulativeAmount = acc.cumulativeAmount + obj.dailyAmount)
}.drop(1)
e
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