Coordination of templates by functional parameters
I have a vector of tuples
val l = for {i <- 1 to 5} yield (i,i*2)
Vector((1,2), (2,4), (3,6), (4,8), (5,10))
and I would like to summarize it like this:
l.reduce((x,y) => (x._1+y._1, x._2+y._2))
(15,30)
but using pattern matching.
I know how to do this if the function only receives one parameter, i.e. l.map({case(a,b)=>a+b})
but I can't get it to work with two parameters. this is what i tried to do:
l.reduce({(case(a,b),case(c,d))=>(a+c,b+d)})
but that won't work.
So my question is, how can I unpack the 2 tuples that come in as parameters to a function?
source to share
Just specify the type explicitly to help the partial function mechanism:
l.reduce[(Int, Int)]{ case ((a,b), (c, d)) => (a + b, c + d)}
Without [(Int, Int)]
scala cannot infer the correct type for your partial function
PS If you overlap, why are you seeing this error about String
no matter what type you actually use (this is Int
in your case):
found : Any ,
required: String
This is because of the implicit "+" for strings in Predef
. This is not the only problem with this implicit one - you can take a look at SI-194 .
Even without this:
l.reduce{ case ((a,b), (c, d)) => (a, d)}
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, ?) => ?
scala was unable to infer the type because it cannot infer the type for the partial function - can be any Int: supertype (A1, A1) => A1
expected, where[A1 >: A]
source to share