Skip to content

Instantly share code, notes, and snippets.

@telekosmos
Last active January 14, 2022 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save telekosmos/dae6d951f92b7cdf0e9e7b23292a3c9e to your computer and use it in GitHub Desktop.
Save telekosmos/dae6d951f92b7cdf0e9e7b23292a3c9e to your computer and use it in GitHub Desktop.
How for comprehensions relate to map/flatMap as syntactic sugar in Scala
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