Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing two maps

Is there a function in Scala to compose two maps or is flatMap a sensible approach?

scala> val caps: Map[String, Int] = Map(("A", 1), ("B", 2))
caps: Map[String,Int] = Map(A -> 1, B -> 2)

scala> val lower: Map[Int, String] = Map((1, "a"), (2, "b"))
lower: Map[Int,String] = Map(1 -> a, 2 -> b)

scala> caps.flatMap {
     | case (cap, idx) => Map((cap, lower(idx)))
     | }
res1: scala.collection.immutable.Map[String,String] = Map(A -> a, B -> b)

Some syntactic sugar would be great!

like image 583
tysonjh Avatar asked Nov 26 '12 17:11

tysonjh


1 Answers

If you know lower will contain keys for all the values in caps, you can use mapValues:

scala> caps mapValues lower
res0: scala.collection.immutable.Map[String,String] = Map(A -> a, B -> b)

If you don't want or need a new collection, just a mapping, it's a little more idiomatic to use andThen:

scala> val composed = caps andThen lower
composed: PartialFunction[String,String] = <function1>

scala> composed("A")
res1: String = a

This also assumes there aren't values in caps that aren't mapped in lower.

like image 151
Travis Brown Avatar answered Sep 28 '22 06:09

Travis Brown