This question already has an answer here:
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?
Going for a literal translation, let's try this:
Scala's
groupBy
makes this more complex than it needs to be -- there have been calls forgroupWith
orgroupInto
, but they didn't make Odersky's standard for standard library inclusion.Recall
group
from the Data.List library,giving us:
a list-friendly and relatively "naive" implementation.
Another implementation: