Created
April 26, 2012 07:22
-
-
Save killerswan/2497124 to your computer and use it in GitHub Desktop.
Haskell back in awk's order of magnitude <_<
This file contains hidden or 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
| -- Kevin Cantu | |
| -- April 2012 | |
| import Control.Monad (when) | |
| import Data.Map (Map) | |
| import Data.List | |
| import Data.List.Split | |
| import qualified Data.Map as M | |
| import System.Environment | |
| import System.IO | |
| import Text.CSV | |
| import Text.Printf | |
| -- read a CSV file | |
| loadCSV path = | |
| do | |
| eitherRecs <- parseCSVFromFile path | |
| let records = case eitherRecs | |
| of Left e -> error . show $ e | |
| Right recs -> recs | |
| return records | |
| -- create a location map: (lat,lon) --> count | |
| newMap :: Map String Integer | |
| newMap = M.fromList [] | |
| -- increment a count | |
| updateMap mm key = M.insertWith' (+) key 1 mm | |
| -- read | |
| readCoord line = | |
| case length fields | |
| of | |
| 2 -> fields !! 1 | |
| _ -> error "wrong size record: " ++ show line | |
| where | |
| fields = splitOn "," line | |
| -- arg0 is the CSV file | |
| getInputFile args = | |
| if length args == 1 | |
| then args !! 0 | |
| else error "usage: count csvInputFile" | |
| -- logging | |
| verbose = True | |
| now xx = when verbose (putStrLn xx) | |
| main = | |
| do | |
| args <- getArgs | |
| now "counting IPs per coordinate..." | |
| recs <- readFile $ getInputFile args | |
| let coordsMap = foldl' updateMap newMap . map readCoord . lines $ recs | |
| now "saving/printing..." | |
| putStrLn . show $ coordsMap | |
| now "ok." | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment