Scala 计算元素的出现次数
在Haskell中,计算列表中的所有元素是一行:Scala 计算元素的出现次数,scala,list,haskell,dictionary,list-comprehension,Scala,List,Haskell,Dictionary,List Comprehension,在Haskell中,计算列表中的所有元素是一行: count xs = toList (fromListWith (+) [(x, 1) | x <- xs]) 这个函数在Scala中也能如此优雅地表达吗?从Data.List库中调用group scala> "haskell scala".groupBy(identity).mapValues(_.size).toSeq res1: Seq[(Char, Int)] = ArrayBuffer((e,1), (s,2), (a,3
count xs = toList (fromListWith (+) [(x, 1) | x <- xs])
这个函数在Scala中也能如此优雅地表达吗?从Data.List库中调用
group
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))
group :: [a] -> [[a]]
给我们:
map (head &&& length) . group . sort
一个列表友好且相对“幼稚”的实现。对于直译,让我们尝试一下:
// 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的
groupBy
使这个问题变得比它需要的更复杂——有人呼吁使用groupWith
或groupInto
,但他们没有制定Odersky的标准库包含标准。另一个实现:
def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
这是对shorter的奇怪定义;)但至少它也是一条单行线;)@尼古拉斯,当我写这篇文章的时候,我没有
.toSeq
。)现在删除它。哇,我不知道&&&
操作符,很酷!虽然这很酷,问题是如何在Scala中实现这一点。这个问题被错误地认为在Haskell中使用中间容器和列表理解是一种优雅的方法:)在时间复杂性方面,您的解决方案与我的解决方案相比如何?@fredwolf它们具有相同的复杂性。无意义的版本:toList。fromListWith(+)。map(,1)
@sdcvvc现在是标准的元组部分Haskell?不是H2010,而是IMO pretty standard。@sdcvvc在哪里可以找到这个“IMO pretty standard”?;)
def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))