Why is there no mapKeys in Scala?

The Scala collection library has mapValues and filterKeys . The reason it does not have mapKeys is most likely the performance aspect (regarding the implementation of the HashMap ), as discussed here for Haskell: Why is there no mapKeys in Data.Hashmap?

However.

Due to the performance implications, I need mapKeys no less than mapValues , just for massaging the data (i.e. I use the map to abstract the data, not its sampling speed).

I'm wrong and what data model would you use for this? Tuple?

+5
source share
2 answers

I don’t know why this is not in the standard library, but you can easily pimp your library with an implicit class

  implicit class MapFunctions[A, B](val map: Map[A, B]) extends AnyVal { def mapKeys[A1](f: A => A1): Map[A1, B] = map.map({ case (a, b) => (f(a), b) }) } val m = Map(1 -> "aaa", 2 -> "bbb") println(m.mapKeys(_ + 1)) 
+10
source

You can use scalaz:

 import scalaz.Scalaz._ val m = Map(1 -> "aaa", 2 -> "bbb") m.mapKeys(_ + 1) 

In case of collisions, the result may be less than the original map.

+2
source

Source: https://habr.com/ru/post/1208831/


All Articles