Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

David R. MacIver http://unenterprise.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Simple Haskell script for word counting

This is just a simple piece of code I put together to play with some Haskell when I realised I've not been writing nearly enough of the stuff.

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  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS