代码之家  ›  专栏  ›  技术社区  ›  RAQ

Scala ReduceLeft的行为

  •  1
  • RAQ  · 技术社区  · 8 年前

    在下面的代码片段中,我使用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)
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   soote    8 年前

    这是因为您没有从列表中的第一个值中减去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)) 
    
        2
  •  2
  •   Leo C    8 年前

    我想 foldLeft 提供更好的清晰度,但您仍然可以使用 reduceLeft 在列表的前面加上 0 作为初始值:

    (0 :: list).reduceLeft((total, cur) => total + Math.abs(x - cur))