count occurrences of elements [duplicate]

2019-01-23 12:43发布

问题:

This question already has an answer here:

  • Scala how can I count the number of occurrences in a list 14 answers

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?

回答1:

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))


回答2:

Recall group from the Data.List library,

group :: [a] -> [[a]]

giving us:

map (head &&& length) . group . sort

a list-friendly and relatively "naive" implementation.



回答3:

Another implementation:

def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))


回答4:

Going for a literal translation, let's try this:

// Implementing this one in Scala
def fromSeqWith[A, B](s: Seq[(A, B)])(f: (B, B) => B) =
    s groupBy (_._1) mapValues (_ map (_._2) reduceLeft f)

def count[A](xs: Seq[A]) = fromSeqWith(xs map (_ -> 1))(_+_).toSeq

Scala's groupBy makes this more complex than it needs to be -- there have been calls for groupWith or groupInto, but they didn't make Odersky's standard for standard library inclusion.