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, and the rest of it is so simple that it mostly works the first time you write it. If you ignore the setup of the input data, the code is effectively...