Scala ReduceLeft 的行为
Behaviour of Scala ReduceLeft
在下面的代码片段中,我使用 reduceLeft 和 foreach 循环来查找一个数字与所有列表成员的差异之和。我原以为这两个结果是相同的 (1050),但 reduceLeft 在最终答案中增加了额外的 50 (val x)。这背后的原因是什么?
val list = List(200,400,600)
val x = 50
println(list.reduceLeft((total, cur) => total + Math.abs(x - cur)))
var total = 0l
list.foreach(p => {
total = total + Math.abs(x - p)
})
println(total)
这是因为您没有从列表中的第一个值中减去 50。您的 reduceLeft 函数正在执行此操作:
Iteration 1: 200 + Math.abs(50 - 400)
Iteration 2: 550 + Math.abs(50 - 600)
Result: 1100
尝试使用 foldLeft
list.foldLeft(0)((total, cur) => total + Math.abs(50 - cur))
我认为 foldLeft
更清晰,但您仍然可以使用 reduceLeft
,方法是在列表前加上 0
作为初始值:
(0 :: list).reduceLeft((total, cur) => total + Math.abs(x - cur))
在下面的代码片段中,我使用 reduceLeft 和 foreach 循环来查找一个数字与所有列表成员的差异之和。我原以为这两个结果是相同的 (1050),但 reduceLeft 在最终答案中增加了额外的 50 (val x)。这背后的原因是什么?
val list = List(200,400,600)
val x = 50
println(list.reduceLeft((total, cur) => total + Math.abs(x - cur)))
var total = 0l
list.foreach(p => {
total = total + Math.abs(x - p)
})
println(total)
这是因为您没有从列表中的第一个值中减去 50。您的 reduceLeft 函数正在执行此操作:
Iteration 1: 200 + Math.abs(50 - 400)
Iteration 2: 550 + Math.abs(50 - 600)
Result: 1100
尝试使用 foldLeft
list.foldLeft(0)((total, cur) => total + Math.abs(50 - cur))
我认为 foldLeft
更清晰,但您仍然可以使用 reduceLeft
,方法是在列表前加上 0
作为初始值:
(0 :: list).reduceLeft((total, cur) => total + Math.abs(x - cur))