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, ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.