Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no mapKeys in Scala?

The Scala Collection library has mapValues and filterKeys. The reason it doesn't have mapKeys is likely the performance aspect (with regard to HashMap implementation), as discussed here for Haskell: Why there's not mapKeys in Data.Hashmap?

However.

Performance implications aside, I find myself needing mapKeys at least as much as mapValues, simply for massaging data (i.e. I'm using a map for data abstraction, not for its fetch speed).

Am I wrong, and which data model would you use for this? Tuples?

like image 521
akauppi Avatar asked Dec 11 '14 16:12

akauppi


1 Answers

No idea why it's not in standard library, but you can easily pimp your library with 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))
like image 97
Eugene Zhulenev Avatar answered Nov 09 '22 03:11

Eugene Zhulenev