Created
July 14, 2015 03:25
-
-
Save davenportw15/c3bae1574d81d03c6200 to your computer and use it in GitHub Desktop.
Map counter in Haskell
This file contains 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 Data.Map (Map) | |
import qualified Data.Map as Map | |
import Control.Monad | |
-- | Returns a Map with counts of items in a list | |
count :: (Ord a, Integral b) => [a] -> Map a b | |
count = | |
foldr updateMap Map.empty | |
where updateMap v counts | |
| Map.member v counts = Map.adjust succ v counts | |
| otherwise = Map.insert v 1 counts | |
main = do | |
putStrLn "Enter words to be counted, separated by spaces" | |
input <- fmap words getLine | |
let counted = Map.toList (count input) | |
forM_ counted (\(key, value) -> | |
putStrLn $ concat [key, ": ", show value]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment