Last active
January 14, 2022 16:53
-
-
Save telekosmos/dae6d951f92b7cdf0e9e7b23292a3c9e to your computer and use it in GitHub Desktop.
How for comprehensions relate to map/flatMap as syntactic sugar in Scala
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
val l1 = List(1,3,5,7) | |
val l2 = List(2,4,6,8) | |
val result = for { | |
x <- l1 | |
y <- l2 | |
} yield x * y | |
val flatMapResult = l1.flatMap(i => l2.map(_ * i)) | |
// println(s"result: $result **vs** flatMapResult: $flatMapResult") | |
val endResult = result.zip(flatMapResult).forall(e => e._1 == e._2) | |
println(s"End result: both are ${if (endResult) "equals" else "different"}") // equals |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment