Last active
December 14, 2015 20:29
-
-
Save davidandrzej/5144459 to your computer and use it in GitHub Desktop.
Scala Map.keys returns an Iterable that happens to be backed by a Set so if you map() over it you get Set-like behavior. Good times.
This file contains 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
// Map.keys returns an Iterable that happens to be backed by a Set so | |
// if you map() over it you get Set-like behavior. Good times. | |
// | |
// $ scalac TrickyMapKeys.scala | |
// $ scala TrickyMapKeys | |
// keys mod 2 (VERSION A): Set(0, 1) | |
// keys mod 2 (VERSION B): List(0, 0, 1, 0) | |
// | |
object TrickyMapKeys extends App { | |
val keyValuePairs = Seq(2 -> "deux", 0 -> "al cifr", 5 -> "cinco", 4 -> "fore") | |
val m = Map(keyValuePairs:_*) | |
val keysModTwoA = m.keys.map(_ % 2) | |
val keysModTwoB = m.map(_._1 % 2) | |
println(s"keys mod 2 (VERSION A): ${keysModTwoA.toString}") | |
println(s"keys mod 2 (VERSION B): ${keysModTwoB.toString}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment