O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Pipes and filters – the Scala version

Here is the Scala version. The for comprehension is similar in spirit to the preceding Unix shell pipe line:

object InvertedIdx extends App {
  val m = List("Carr" -> "And So To Murder",
          "Carr" -> "The Arabian Nights Murder",
          "Carr" -> "The Mad Hatter Mystery",
          "Christie" -> "The Murder Of Roger Ackroyd",
          "Christie" -> "The Sittaford Mystery",
          "Carr" -> "The Plague Court Murders") // 1
  val ignoreWordsSet = Set("To", "The", "And", "So", "Of") // 2
  val invertedIdx = (for { // 3
    (k, v) <- m // 4
    w <- v.split("\\W") // 5
    if !ignoreWordsSet.contains(w) // 6
  }
    yield(w -> k)).groupBy(_._1).map { case (k,v) => (k,v.map(_._2))} // 7
  println(invertedIdx)
}

The code is simple. We just write the code for comprehension, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required