Simple Haskell script for word counting
It reads text from stdin and prints the words it finds together with how many times each one occurred.
1 2 module Main 3 where 4 5 import List 6 import Control.Arrow 7 8 type Comparator a = (a -> a -> Ordering) 9 10 ascending :: (Ord a) => (b -> a) -> Comparator b 11 ascending f x y = compare (f x) (f y) 12 13 descending :: (Ord a) => (b -> a) -> Comparator b 14 descending = flip . ascending 15 16 secondary :: Comparator a -> Comparator a -> Comparator a 17 secondary f g x y = case f x y of { 18 EQ -> g x y; 19 z -> z; } 20 21 -- Returns a list of unique elements together with their frequency. Listed in decreasing order of frequency, followed by 22 increasing order of the elements. 23 count :: (Ord a) => [a] -> [(a, Int)] 24 count = map (head &&& length) . sortBy (descending length `secondary` ascending head) . group . sort 25 26 main :: IO () 27 main = interact $ unlines . map (\(x, y) -> (take 20 $ x ++ repeat ' ') ++ " : " ++ show y) . count . words 28