New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Surprising behavior when performing flatmap on Maps whose values are Lists of 2-tuples #5364
Comments
Imported From: https://issues.scala-lang.org/browse/SI-5364?orig=1 |
@paulp said: |
Tom Dong (tomtung) said: |
@paulp said: scala> m.toList flatMap (_._2)
res0: List[(Int, Int)] = List((1,11), (1,111), (2,22), (2,222)) |
Tom Dong (tomtung) said (edited on Jan 10, 2012 8:08:32 AM UTC):
So this is not my "personal" interpretation. If you execute: You get a List of List, and concatenate them gives a List, not a Map. "Operate on a collection, and get a new collection of the same type" seems to be a nice idea, but I don't think it automatically justifies the resultant semantic confusions. I think the problem here is that flatMapping a Map does not always return a Map. This happens only when the values of the map happens to be collections of 2-tuples - but 2-tuples are not exclusively used as Map elements. IMHO, this inconsistency can be problematic. |
@paulp said: |
Tom Dong (tomtung) said: |
scala> val m = Map("a" -> List(11,111), "b" -> List(22,222))
m: scala.collection.immutable.Map[java.lang.String,List[Int]] = Map(a -> List(11, 111), b -> List(22, 222))
scala> m.flatMap(_._2) // Expected behavior
res9: scala.collection.immutable.Iterable[Int] = List(11, 111, 22, 222)
scala> val m = Map("a" -> List(1 -> 11,1 -> 111), "b" -> List(2 -> 22,2 -> 222))
m: scala.collection.immutable.Map[java.lang.String,List[(Int, Int)]] = Map(a -> List((1,11), (1,111)), b -> List((2,22), (2,222)))
scala> m.flatMap(_._2) // Surprising behavior, a map is created and 2 tuples are missing(overwritten)
res8: scala.collection.immutable.Map[Int,Int] = Map(1 -> 111, 2 -> 222)
The text was updated successfully, but these errors were encountered: