// FOR is very unlike for in Java val xss = List(List(1,2),List(3,4)) for (xs <- xss) { for (x <- xs) print(x + "\t") println() } // is really just a special case of the general // FOR comprehension which returns a result for // each iteration and collects it into a list: for (p <- persons if p.age > 20) yield p.name // is equivalent to persons filter (p => p.age > 20) map (p => p.name) /* generally: for ( s ) yield e s is a sequence of generators, definitions and filters. generators: x <- e where e is a list (or expression resulting in a list) definitions: val x = e filters: boolean expression */ // sometimes more readable than map/filter/... { i <- List.range(1, n) j <- List.range(1, i) if isPrime(i+j) } yield {i, j} // n-queens example ... // similar to SQL select statements case class Book(title: String, authors: List[String]) val books: List[Book] = List( Book("Structure and Interpretation of Computer Programs", List("Abelson, Harold", "Sussman, Gerald J.")), Book("Principles of Compiler Design", List("Aho, Alfred", "Ullman, Jeffrey")), Book("Programming in Modula-2", List("Wirth, Niklaus")), Book("Introduction to Functional Programming", List("Bird, Richard")), Book("The Java Language Specification", List("Gosling, James", "Joy, Bill", "Steele, Guy", "Bracha, Gilad"))) /* try * for (b <- books; a <- b.authors if a startsWith "Ullman") yield b.title for (b <- books if (b.title indexOf "Program") >= 0) yield b.title and similar */ // translation of FOR only depends on map, flatMap, and filter (see 10.4) // therefore if your container implements these, you can use FOR def map[B](f: A => B): C[B] def flatMap[B](f: A => C[B]): C[B] def filter(p: A => Boolean): C[A]