Then, to find the titles of all books whose author’s last name is “Gosling”:
scala> for (b <- books; a <- b.authors if a startsWith "Gosling")
yield b.title
res4: List[String] = List(The Java Language Specification)
Or, to find the titles of all books that have the string “Program” in their title:
scala> for (b <- books if (b.title indexOf "Program") >= 0) yield b.title
res5: List[String] = List(Structure and Interpretation of Computer Programs, Programming in Modula-2, Elements
of ML Programming)
Or, to find the names of all authors that have written at least two books in the database:
scala> for (b1 <- books; b2 <- books if b1 != b2;
a1 <- b1.authors; a2 <- b2.authors if a1 == a2) yield a1
res6: List[String] = List(Ullman, Jeffrey, Ullman, Jeffrey)
The last solution is not yet perfect, because authors will appear several times in the list of results. You still need to remove duplicate authors from result lists. This can be achieved with the following function:
scala> def removeDuplicates[A](xs: List[A]): List[A] = { if (xs.isEmpty) xs
else
xs.head :: removeDuplicates(
xs.tail filter (x => x != xs.head)
)
}
removeDuplicates: [A](xs: List[A])List[A]
scala> removeDuplicates(res6)
res7: List[String] = List(Ullman, Jeffrey)
It’s worth noting that the last expression in method removeDuplicates can be equivalently expressed using a for expression: