Daniele B
01/29/2021, 5:25 PMdata 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?ephemient
01/29/2021, 5:28 PMDaniele B
01/29/2021, 5:29 PMephemient
01/29/2021, 5:29 PMlist.foldMap(0) { acc, element ->
val cumulativeAmount = acc + element.dailyAmount
cumulativeAmount to element.copy(cumulativeAmount = cumulativeAmount)
}
nanodeath
01/29/2021, 5:37 PMephemient
01/29/2021, 5:43 PMmapAccum
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)tseisel
01/30/2021, 9:44 AMrunningFold
!
list.runningFold(list.first()) { acc, obj ->
obj.copy(cumulativeAmount = acc.cumulativeAmount + obj.dailyAmount)
}.drop(1)
ephemient
01/30/2021, 12:52 PM