Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting unique elements in a list

Is there a straight-forward combination of standard higher-order functions to count the unique elements in a list?

For example the result for

[1, 1, 4, 0, 4, 4]

would be something like

[(1,2), (4,3), (0,1)]
like image 870
LennyStackOverflow Avatar asked Sep 14 '10 16:09

LennyStackOverflow


People also ask

How do you count the number of unique items in an Excel list?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.


2 Answers

If order is not important this works:

map (\xs@(x:_) -> (x, length xs)) . group . sort

group . sort will give you a list of lists where all elements that are equal to each other are grouped into the same sublist (without sort, only consecutive equal elements would be grouped together). The map then turns each sublist into a (element, lengthOfSublist)-tuple.

If you want to order the result by first occurrence, you can use zip before the sort to add an index to each element, then, after grouping, sort again by that index and then remove the index.

like image 57
sepp2k Avatar answered Oct 26 '22 16:10

sepp2k


The simplest thing would be to sort the items into order, use "group" to put them into sub-lists of equal elements, and then count the items in each sub-list.

map (\xs -> (head xs, length xs)) . group . sort
like image 37
Paul Johnson Avatar answered Oct 26 '22 17:10

Paul Johnson