Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Last active December 19, 2015 17:09
Show Gist options
  • Save dtchepak/5989109 to your computer and use it in GitHub Desktop.
Save dtchepak/5989109 to your computer and use it in GitHub Desktop.
Count number of occurrences of each item in a list
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