WordCount.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{-
Copyright 2014 Bas Bossink (bas.bossink@gmail.com).
-}
module WordCount (wordCount) where

import Data.Char (isAlphaNum, toLower)
import Data.Foldable (foldl')
import Data.Map.Strict (Map, empty, insertWith)

wordCount :: String -> Map String Integer
wordCount = tallyWords . words . map normalize

tallyWords :: [String] -> Map String Integer
tallyWords = foldl' tallyWord empty 
  where 
  tallyWord accumulator word = insertWith (+) word 1 accumulator

normalize :: Char -> Char
normalize c 
  | isAlphaNum c = toLower c
  | otherwise = ' '

@sjakobi and @etrepum think this looks great

Comments

Decided to follow up with a revision of iteration 7. I believe this solution is easier to read and understand than the use of the fromListWith construction in iteration 8. Normalizing the input first using the noramlize function, shamelessly stolen from sjakobi's word-count also cleans up tallyWords quite a lot. I've tried to simplify tallyWord but can't seem to find anything that is easier to read/understand. Any suggestions?

basbossink commented 19 March 2014 at 21:44 UTC

I'll take the copying as an implicit compliment :)

I think that tallyWords is a lot clearer now!

sjakobi commented 19 March 2014 at 22:19 UTC

Mine is a lot shorter (50%) but arguably not as readable.

houshuang commented 20 March 2014 at 00:53 UTC

You're not logged in right now. Please login via GitHub to comment