【问题标题】:Behaviour of Scala ReduceLeftScala ReduceLeft 的行为
【发布时间】:2018-06-27 19:20:27
【问题描述】:

在下面的代码 sn-p 中,我使用 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)

【问题讨论】:

    标签: scala reduce


    【解决方案1】:

    这是因为您没有从列表中的第一个值中减去 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 更有意义。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-03
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2021-08-18
      • 2023-03-10
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多