1

In the following code snippet I'm using reduceLeft and foreach loop to find the sum of the differences of a number against all of the list members. I was expecting that the result from these two would be the same (1050) but reduceLeft is adding extra 50 (val x) in final answer. What is the reason behind that?

  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)
RAQ
  • 119
  • 8

2 Answers2

3

This is because you are not subtracting 50 from the first value in the list. Your reduceLeft function is doing this:

Iteration 1: 200 + Math.abs(50 - 400)
Iteration 2: 550 + Math.abs(50 - 600)
Result: 1100

Try using foldLeft

list.foldLeft(0)((total, cur) => total + Math.abs(50 - cur)) 
soote
  • 3,240
  • 1
  • 23
  • 34
2

I think foldLeft gives better clarity, but you can still use reduceLeft by prepending the list with a 0 to serve as the initial value:

(0 :: list).reduceLeft((total, cur) => total + Math.abs(x - cur))
Leo C
  • 22,006
  • 3
  • 26
  • 39