下面的代码按预期工作,但映射lambda不纯净。我怎么能重构它使它变得纯粹呢。(不需要坚持调用地图,我们可以在这里减少或其他任何东西,我只希望它是纯的(
val entries = listOf(
Pair(LocalDate.now().minusDays(2), 1),
Pair(LocalDate.now().minusDays(1), 2),
Pair(LocalDate.now().minusDays(0), 3)
)
private fun buildSumSchedule(entries: List<Pair<LocalDate, Double>>): Map<LocalDate, Double> {
var runningSum = 0.0
return entries.sortedBy { it.first }.map {
runningSum += it.second
it.copy(second = runningSum)
}.toMap()
}
val sumSchedule = buildSumSchedule(entries)
这里需要的是scanReduce
,这就是排序后如何使用上一个项目
@ExperimentalStdlibApi
private fun buildSumSchedule(entries: List<Pair<LocalDate, Double>>): Map<LocalDate, Double> =
entries.sortedBy { it.first }.scanReduce { pair, acc ->
acc.copy(second = pair.second + acc.second)
}.toMap()
来自kotlin1.4.0runningReduce
private fun buildSumSchedule(entries: List<Pair<LocalDate, Double>>): Map<LocalDate, Double> =
entries.sortedBy { it.first }.runningReduce{acc, pair ->
acc.copy(second = pair.second + acc.second)
}.toMap()