Wednesday, October 05, 2011

Scala By Example Chapter 10 Solutions - Exercise 10.3.2

Exercise 10.3.2 Translate the following for comprehensions to higher-order functions.

object ForToMap {
def main(args: Array[String]) {
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 Modula2",
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")))
println("All books with authors starting with the word 'Bird': " +
books.flatMap(b => b.authors.filter(a => a startsWith "Bird").map(a => b.title)))
println("All books with the word 'Program' in it: " +
books.filter(b => (b.title indexOf "Program") >= 0).map(b => b.title))
}
}
view raw ForToMap.scala hosted with ❤ by GitHub

No comments: