How to group and count in haskell? -


given list (for instance [1,2,2,3,3,4,5,6]) how possible group , count them according bins/range? able specify range, that:

say range=2, , using previous list, give me [1, 4, 2, 1], given there's 1 0's or 1's, 4 2's or 3's, 2 4's or 5's , 1 6's or 7's.

say range=4, , using previous list, give me [5, 3], given there's 5 0's or 1's or 2's or 3's, 3 4's or 5's or 6's or 7's.

i have looked group , groupby not found appropriate predicates, , histogram-fill library. latter seems nice create bins, not find out how load data bins.

how can achieve this?

my attempt on 1 of suggestions below:

import data.list  import data.function   quantize range n = n `div` range    main = print (groupby ((==) `on` quantize 4) [1,2,3,4,2])  

the output [[1,2,3],[4],[2]] when should have been [[1,2,2,3],[4]]. both suggestions below works on sorted lists.

main = print (groupby ((==) `on` quantize 4) (sort [1,2,3,4,2]))    

you'll need quantize in order definitions of bins.

-- `quantize range n` rounds n down nearest multiple of range quantize :: int -> int -> int 

groupby takes "predicate" argument*, identifies whether 2 items should placed in same bin. so:

groupby (\n m -> quantize range n == quantize range m) :: [int] -> [[int]] 

will group elements whether in same bin, without changing elements. if range 2, give like

[[1],[2,2,3,3],[4,5],[6]] 

then have take length of each sublist.

* there's neat function called on allows write predicate more succinctly

groupby ((==) `on` quantize range) 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -