Created
May 1, 2013 19:45
-
-
Save ryanlecompte/5497801 to your computer and use it in GitHub Desktop.
Tricky scala collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Beware of iterating/yielding over multiple collections with a Set in the middle. | |
// Due to Scala's desire to keep intermediate type, you'll inadvertantly remove | |
// duplicates from the inner collection. This may or may not be desirable depending | |
// on your use case. | |
// Note Set in the middle. This yields the correct value because the last collection has no duplicates. | |
scala> for (a <- List(1); b <- Set(1); c <- List(1,2)) yield (a,c) | |
res6: List[(Int, Int)] = List((1,1), (1,2)) | |
// Note the Set in the middle. This gets rid of duplicates in List(1,1) due to the Set before it! This may or may not | |
// be desirable. | |
scala> for (a <- List(1); b <- Set(1); c <- List(1,1)) yield (a,c) | |
res7: List[(Int, Int)] = List((1,1)) | |
// Note that we changed the middle collection from Set to Seq. This does not get rid of duplicates. | |
scala> for (a <- List(1); b <- Seq(1); c <- List(1,1)) yield (a,c) | |
res8: List[(Int, Int)] = List((1,1), (1,1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment