Friday, October 16, 2015

Simulate database queries with for expression in Scala

Note that there are 3 different implementations for removal of duplicates.

object Example {

  case class Book(title: String, authors: String*)

  val books: List[Book] = List(
    Book(
      "Structure and Interpretation of Computer Programs",
      "Abelson, Harold", "Sussman, Gerald J."
    ),
    Book(
      "Principles of Compiler Design",
      "Aho, Alfred", "Ullman, Jeffrey"
    ),
    Book(
      "Programming in Modula-2",
      "Wirth, Niklaus"
    ),
    Book(
      "Elements of ML Programming",
      "Ullman, Jeffrey"
    ),
    Book(
      "The Java Language Specification", "Gosling, James",
      "Joy, Bill", "Steele, Guy", "Bracha, Gilad"
    )
  )
}


object Test {

  import Example._

  for {
    b <- books
    a <- b.authors
    if a startsWith("Gosling")
  } yield b.title

  for {
    b <- books
    if (b.title indexOf "Program" ) >= 0
  } yield b.title

  for {
    b1 <- books
    b2 <- books
    if b1 != b2
    a1 <- b1.authors
    a2 <- b2.authors
    if a1 == a2
  } yield a1

  def removeDuplicated[A](xs: List[A]): List[A] = {
    if(xs.isEmpty) xs
    else {
      val y = removeDuplicated(xs.tail)
      if(y.contains(xs.head)) y
      else xs.head :: y
    }
  }

  def removeDuplicated1[A](xs: List[A]): List[A] = {
    if(xs.isEmpty) xs
    else {
      xs.head :: removeDuplicated1(
        xs.tail.filter(x => x != xs.head)
      )
    }
  }

  def removeDuplicated2[A](xs: List[A]): List[A] = {
    if(xs.isEmpty) xs
    else {
      xs.head :: removeDuplicated2(
        for {
          x <- xs.tail
          if x != xs.head
        } yield x
      )
    }
  }


  removeDuplicated(List(1, 1, 2, 2, 3))
  removeDuplicated1(List(1, 1, 2, 2, 3))
  removeDuplicated2(List(1, 1, 2, 2, 3))


  val profilicAuthors = for {
    b1 <- books
    b2 <- books
    if b1 != b2
    a1 <- b1.authors
    a2 <- b2.authors
    if a1 == a2
  } yield a1

  removeDuplicated(profilicAuthors)
  removeDuplicated1(profilicAuthors)
  removeDuplicated2(profilicAuthors)
}

0 comments: