avatar

Andres Jaimes

Examples of ‘for’ queries with Scala

By Andres Jaimes

On this page you are going to find some examples of ‘for’ queries.
Let’s start by defining the following database:

case class Book(title: String, authors: List[String])

val books: List[Book] = List(
  Book("structure and interpretation of computer programs",
      List("abelson, harald", "sussman, gerald j.")),
  Book("introduction to functional programming",
    List("bird, richard", "wadler, phil")),
  Book("effective java",
    List("bloch, joshua")),
  Book("java puzzlers",
    List("bloch, joshua", "gafter, neal")),
  Book("programming in scala",
    List("odersky, martin", "spoon, lex", "venners, bill"))
)

Find the titles of books whose author’s name is ‘bird’

for {
  b <- books
  a <- b.authors
  if a startsWith "bird"
} println(a)

prints

bird, richard

Find all the books which have the work ‘program’ in the title

for {
  b <- books
  if b.title contains "program"
} println(b)

prints

Book(structure and interpretation of computer programs,List(abelson, harald, sussman, gerald j.))
Book(introduction to functional programming,List(bird, richard, wadler, phil))
Book(programming in scala,List(odersky, martin, spoon, lex, venners, bill))

Find the names of all authors who have written at least two books present in the database

val authors = {
  for {
    b1 <- books
    b2 <- books
    if b1 != b2
    a1 <- b1.authors
    if b2.authors.contains(a1)
  } yield a1
}.distinct

println(authors)

prints

List(bloch, joshua)

Happy coding.