Count occurrences of each element in a List[List[T]] in Scala

scala, scala-collections

Solution

docs.flatten.foldLeft(new Map.WithDefault(Map[String,Int](),Function.const(0))){
  (m,x) => m + (x -> (1 + m(x)))}

What a train wreck!

[Edit]

Ah, that's better!

docs.flatten.foldLeft(Map[String,Int]() withDefaultValue 0){
  (m,x) => m + (x -> (1 + m(x)))}

Problem

Suppose you have ``` val docs = List(List("one", "two"), List("two", "three")) ``` where e.g. List("one", "two") represents a document containing terms "one" and "two", and you want to build a map with the document frequency for every term, i.e. in this case ``` Map("one" -> 1, "two" -> 2, "three" -> 1) ``` How would you do that in Scala? (And in an efficient way, assuming a much larger dataset.) My first Java-like thought is to use a mutable map: ``` val freqs = mutable.Map.empty[String,Int] for (doc <- docs) for (term <- doc) freqs(term) = freqs.getOrElse(term, 0) + 1 ``` which works well enough but I'm wondering how you could do that in a more "functional" way, without resorting to a mutable map?

Original source

Related problems