Given a simple sequence:
scala> val a = Seq(1.0,2.0,3.0)
res8: Seq[Double] = List(1.0, 2.0, 3.0)
Let us add them up!
scala> a.reduceLeft{_ + _}
res6: Double = 6.0
But how to be explicit with the parameters? Here is my attempt:
scala> a.reduceLeft{case(b,c) => b+c}
Well .. no .. We have a type mismatch:
<console>:9: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, Double) => ?
a.reduceLeft{case(b,c) => b+c}
^
<console>:9: error: type mismatch;
found : Any
required: String
a.reduceLeft{case(b,c) => b+c
But even when I add in the types explicitly it does not work:
scala> a.reduceLeft{case(b:Double,c:Double) => b+c}
<console>:9: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, Double) => ?
a.reduceLeft{case(b:Double,c:Double) => b+c}
So what is going on here?
reduceLeft
takes a Function2
not a Function1
with a tuple input parameter. Thus, you don't need to use case
to pattern match; you just need to name your two input arguments.
The error message is not particularly helpful here, unfortunately, as it does say what it is missing but not in a way that really clearly instructs you on why what you're doing is not right.
Use a.reduceLeft( (a,b) => a + b )
. (Braces are fine too.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With