Created
April 6, 2011 20:52
-
-
Save jorgeortiz85/906503 to your computer and use it in GitHub Desktop.
Scala for-comprehensions
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
// The way Scala for-comprehensions work is that: | |
for (x <- c) f(x) | |
// simply translates to: | |
c.foreach(x => f(x)) | |
// Likewise: | |
for (x <- c) yield f(x) | |
// simply translates to: | |
c.map(x => f(x)) | |
// Something with a guard: | |
for (x <- c if p(x)) yield f(x) | |
// translates* to: | |
c.filter(x => p(x)).map(x => f(x)) | |
// And a nested for: | |
for (x1 <- c1; x2 <- c2) yield f(x1, x2) | |
// translates to: | |
c1.flatMap(x1 => c2.map(x2 => f(x1, x2))) | |
// If the methods in the translation exist, you can use the for-syntax. | |
// *Note: Since Scala 2.8, the guard syntax: | |
for (x <- c if p(x)) yield f(x) | |
// first tries to translate to this: | |
c.withFilter(x => p(x)).map(x => f(x)) | |
// and if the withFilter method doesn't exist, then it translates to this: | |
c.filter(x => p(x)).map(x => f(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment