count occurrences of elements

dictionary, haskell, list, list-comprehension, scala

Solution

scala> "haskell scala".groupBy(identity).mapValues(_.size).toSeq
res1: Seq[(Char, Int)] = ArrayBuffer((e,1), (s,2), (a,3), ( ,1), (l,3), (c,1), (h,1), (k,1))

Problem

Counting all elements in a list is a one-liner in Haskell: ``` count xs = toList (fromListWith (+) [(x, 1) | x <- xs]) ``` Here is an example usage: ``` *Main> count "haskell scala" [(' ',1),('a',3),('c',1),('e',1),('h',1),('k',1),('l',3),('s',2)] ``` Can this function be expressed so elegantly in Scala as well?

Original source

Related problems