scala 计算元素的出现次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10934383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
count occurrences of elements
提问by fredoverflow
Counting all elements in a list is a one-liner in Haskell:
计算列表中的所有元素在 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?
这个函数在 Scala 中也能如此优雅地表达吗?
回答by missingfaktor
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))
回答by Don Stewart
Recall groupfrom the Data.List library,
回忆一下groupData.List 库,
group :: [a] -> [[a]]
giving us:
给我们:
map (head &&& length) . group . sort
a list-friendly and relatively "naive" implementation.
列表友好且相对“幼稚”的实现。
回答by thSoft
Another implementation:
另一种实现:
def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
回答by Daniel C. Sobral
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 groupBymakes this more complex than it needs to be -- there have been calls for groupWithor groupInto, but they didn't make Odersky's standard for standard library inclusion.
ScalagroupBy使这变得比它需要的更复杂——有人呼吁使用groupWithor groupInto,但他们并没有使 Odersky 成为标准库包含的标准。

