Last active
December 19, 2015 17:09
-
-
Save dtchepak/5989109 to your computer and use it in GitHub Desktop.
Count number of occurrences of each item in a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Arrow ((&&&)) | |
import Control.Monad.State | |
import Data.List as L | |
import Data.Map as M | |
import Data.Ord | |
import Data.Traversable | |
type Freq a = [(a,Int)] | |
freq :: Ord a => [a] -> Freq a | |
freq = M.toList . L.foldl' (\acc x -> insertWith (+) x 1 acc) M.empty | |
freq' :: (Ord a, Traversable t) => t a -> Freq a | |
freq' = | |
let updateState a = modify (insertWith (+) a 1) | |
run = flip execState M.empty | |
in M.toList . run . traverse updateState | |
-- from @mwotton: | |
freq'' :: Ord a => [a] -> Freq a | |
freq'' = map (head &&& length) . group . sort |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment