在捕获每个中间结果的同时迭代地对值列表求和的更实用的方法是什么?
What is a more functional way of iteratively summing a list of values while capturing each intermediate result?
下面的代码按预期工作,但映射 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)
你要的是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()
下面的代码按预期工作,但映射 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)
你要的是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()