0

下面的代码按预期工作,但映射 lambda 不纯。我怎样才能重构它以使其纯净。(不需要坚持调用 map,我们可以在这里减少或其他任何东西,我只是希望它是纯的)

    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)
4

1 回答 1

1

你想要的是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()

并从 kotlin 1.4.0 runningReduce

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()
于 2020-08-27T15:00:05.357 回答