Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous parameters working- but not explicit ones - for scala reduceLeft

Tags:

scala

reduce

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?

like image 453
WestCoastProjects Avatar asked Jun 04 '15 19:06

WestCoastProjects


1 Answers

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.)

like image 82
Rex Kerr Avatar answered Sep 27 '22 22:09

Rex Kerr