count occurrences of elements [duplicate]

2019-01-23 12:11发布

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?

4条回答
神经病院院长
2楼-- · 2019-01-23 12:58

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-23 13:10
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))
查看更多
Luminary・发光体
4楼-- · 2019-01-23 13:11

Recall group from the Data.List library,

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

giving us:

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

a list-friendly and relatively "naive" implementation.

查看更多
放荡不羁爱自由
5楼-- · 2019-01-23 13:12

Another implementation:

def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
查看更多
登录 后发表回答