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?
To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.
Tip: If you want to count the duplicates in the whole Column, use this formula =COUNTIF(A:A, A2) (the Column A indicates column of data, and A2 stands the cell you want to count the frequency, you can change them as you need).
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))
Recall group
from the Data.List library,
group :: [a] -> [[a]]
giving us:
map (head &&& length) . group . sort
a list-friendly and relatively "naive" implementation.
Another implementation:
def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With