Exercise 10.3.2 Translate the following for comprehensions to higher-order functions.
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
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)) | |
} | |
} |
No comments:
Post a Comment