daily pastebin goal
57%
SHARE
TWEET

Untitled

a guest May 17th, 2018 87 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. val newMap = Map[String, Double]() /: listOfMaps { (accumulator, m) => ... }
  2.    
  3. def mergeMap[A, B](ms: List[Map[A, B]])(f: (B, B) => B): Map[A, B] =
  4.   (Map[A, B]() /: (for (m <- ms; kv <- m) yield kv)) { (a, kv) =>
  5.     a + (if (a.contains(kv._1)) kv._1 -> f(a(kv._1), kv._2) else kv)
  6.   }
  7.  
  8. val ms = List(Map("hello" -> 1.1, "world" -> 2.2), Map("goodbye" -> 3.3, "hello" -> 4.4))
  9. val mm = mergeMap(ms)((v1, v2) => v1 + v2)
  10.  
  11. println(mm) // prints Map(hello -> 5.5, world -> 2.2, goodbye -> 3.3)
  12.    
  13. mapList reduce (_ ++ _)
  14.    
  15. def combine(m1: Map, m2: Map): Map = {
  16.   val k1 = Set(m1.keysIterator.toList: _*)
  17.   val k2 = Set(m2.keysIterator.toList: _*)
  18.   val intersection = k1 & k2
  19.  
  20.   val r1 = for(key <- intersection) yield (key -> (m1(key) + m2(key)))
  21.   val r2 = m1.filterKeys(!intersection.contains(_)) ++ m2.filterKeys(!intersection.contains(_))
  22.   r2 ++ r1
  23. }
  24.    
  25. class CombiningMap(m1: Map[Symbol, Double]) {
  26.   def combine(m2: Map[Symbol, Double]) = {
  27.     val k1 = Set(m1.keysIterator.toList: _*)
  28.     val k2 = Set(m2.keysIterator.toList: _*)
  29.     val intersection = k1 & k2
  30.     val r1 = for(key <- intersection) yield (key -> (m1(key) + m2(key)))
  31.     val r2 = m1.filterKeys(!intersection.contains(_)) ++ m2.filterKeys(!intersection.contains(_))
  32.     r2 ++ r1
  33.   }
  34. }
  35.  
  36. // Then use this:
  37. implicit def toCombining(m: Map[Symbol, Double]) = new CombiningMap(m)
  38.  
  39. // And finish with:
  40. mapList reduce (_ combine _)
  41.    
  42. def mergeMaps[A,B](collisionFunc: (B,B) => B)(listOfMaps: Seq[scala.collection.Map[A,B]]): Map[A, B] = {
  43.     listOfMaps.foldLeft(Map[A, B]()) { (m, s) =>
  44.       Map(
  45.         s.projection.map { pair =>
  46.         if (m contains pair._1)
  47.           (pair._1, collisionFunc(m(pair._1), pair._2))
  48.         else
  49.           pair
  50.       }.force.toList:_*)
  51.     }
  52.   }
  53.    
  54. def mergeMaps[A,B](collisionFunc: (B,B) => B)(listOfMaps: List[mutable.Map[A,B]]): mutable.Map[A, B] = {
  55.     listOfMaps.foldLeft(mutable.Map[A,B]()) {
  56.       (m, s) =>
  57.       for (k <- s.keys) {
  58.         if (m contains k)
  59.           m(k) = collisionFunc(m(k), s(k))
  60.         else
  61.           m(k) = s(k)
  62.       }
  63.       m
  64.     }
  65.   }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top