Eli Golin Eli Golin - 1 year ago 114
Scala Question

Reduce on tuples

I have the following type:

val l:Seq[(List[Int],Set[Int])] = ...

I am trying to reduce it as follows:

l.reduceLeft {
case ((a1,b1),(a2,b2)) => if((b1 & b2).nomEmpty) ((a1:::a2),(b1 | b2)) else (a1,b1) }

I get the following:

error:Expression of type (List[Int],Set[Int]) doesn't conform to expected type B_

What am I doing wrong?

Answer Source

The signature of reduceLeft looks like this:

def reduceLeft[B >: A](op: (B, A) ⇒ B): B

B is our accumulator and return type. In order for this to compile, we need to help the compiler out a bit and tell it what type we want it to be:

l.reduceLeft[(List[Int], Set[Int])] {
  case ((a1, b1), (a2, b2)) => if ((b1 & b2).nonEmpty) (a1 ::: a2, b1 | b2) else (a1, b1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download