Haskell では、リスト内のすべての要素を数えることはワンライナーです。
count xs = toList (fromListWith (+) [(x, 1) | x <- xs])
使用例を次に示します。
*Main> count "haskell scala"
[(' ',1),('a',3),('c',1),('e',1),('h',1),('k',1),('l',3),('s',2)]
この関数は、Scala でもこれほどエレガントに表現できるでしょうか?
Haskell では、リスト内のすべての要素を数えることはワンライナーです。
count xs = toList (fromListWith (+) [(x, 1) | x <- xs])
使用例を次に示します。
*Main> count "haskell scala"
[(' ',1),('a',3),('c',1),('e',1),('h',1),('k',1),('l',3),('s',2)]
この関数は、Scala でもこれほどエレガントに表現できるでしょうか?
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
Data.List ライブラリからリコールします。
group :: [a] -> [[a]]
私たちに与える:
map (head &&& length) . group . sort
リストフレンドリーで比較的「ナイーブ」な実装です。
別の実装:
def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
文字通りの翻訳に行くので、これを試してみましょう:
// 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
ScalagroupBy
はこれを必要以上に複雑にしています -groupWith
またはgroupInto
の呼び出しがありましたが、標準ライブラリを含めるための Odersky の標準にはなりませんでした。