3

I' am trying to use foldLeft to calculate the sum of all Double in a Vector. Using reduce works fine but I just can't figure out why it doesn't with foldLeft

scala> val prices = Vector(20.0, 9.5,8.4,9.1)
prices: scala.collection.immutable.Vector[Double] = Vector(20.0, 9.5, 8.4, 9.1)

scala> prices reduce (_ + _)
res0: Double = 47.0

scala> prices reduce ((total, price) => total + price)
res1: Double = 47.0

scala> prices foldLeft (0.0) (_ + _)
<console>:9: error: Double(0.0) does not take parameters
              prices foldLeft (0.0) (_ + _)
                                ^

I googled for some examples using foldLeft with Double and the above syntax seems to work

Anyone can explain where the problem is from ?

Thank you

ccheneson
  • 49,072
  • 8
  • 63
  • 68

0 Answers0