1

Using the solution here, I'm adding two maps together and treating them as if they were sparse vectors. So

def addTwoVectors(map1: Map[Int, Double], map2: Map[Int, Double]) = {
  map1 ++ map2.map{ case (k,v) => k -> (v + map1.getOrElse(k,0)) }
}

Now I'd like to make this generic so that

def addTwoMaps[I, D <% Numeric[D]](m1: Map[I, D], m2: Map[I, D]) = {
  m1 ++ m2.map{ case (k,v) => k -> (v + m1.getOrElse(k, 0.asInstanceOf[D])) }
}

Unfortunately, it doesn't seem to work:

error: type mismatch;
found   : D
required: String

So how do I make this function generic?

Community
  • 1
  • 1
JasonMond
  • 1,440
  • 1
  • 16
  • 30

1 Answers1

3

How about this one?

import scala.math.Numeric.Implicits._
def addTwoMaps[I, D](m1: Map[I, D], m2: Map[I, D])(implicit numeric: scala.math.Numeric[D]) = {
  m1 ++ m2.map{ case (k: I,v: D) => k -> (v + m1.getOrElse(k, numeric.zero)) }
}

Cause I don't know which one Numeric I have, I'm taking this info implicitly, and then importing zero method, which is specific for every Numeric type.

Actually, I do believe, that scalaz solution will be much more cleaner and hope that somebody will post it.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228