Skip to content

Instantly share code, notes, and snippets.

@laurentvaills
Forked from loicdescotte/Forcomptran.md
Created November 9, 2012 11:04
Show Gist options
  • Save laurentvaills/4045166 to your computer and use it in GitHub Desktop.
Save laurentvaills/4045166 to your computer and use it in GitHub Desktop.
Scala for comprehension translation helper

#Scala for comprehension translation helper

##Example 1

    for {
         i <- 1 until n
         j <- 1 until i
         if isPrime(i + j)
    } yield (i, j)

is the same as

    (1 until n) flatMap(i =>
         (1 until i) withFilter(j => isPrime(i+j)) map(
               j => (i, j)))

##Example 2

    for {
      b <- books
      a <- b.authors 
      if a startsWith "bob" 
    } yield b.title

or

    for (b <- books; a <- b.authors if a startsWith "bob") yield b.title

is the same as

    books.flatMap(b => b.authors.withFilter(a => a startsWith "bob").map(a => b.title))

or

    books flatMap (b => b.authors withFilter (a => a startsWith "bob") map (a => b.title))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment