Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Created November 6, 2017 16:01
Show Gist options
  • Save timbuckley/8e6fb1dea48cdaa182c514f960af60ec to your computer and use it in GitHub Desktop.
Save timbuckley/8e6fb1dea48cdaa182c514f960af60ec to your computer and use it in GitHub Desktop.
import qualified Data.Map as M (Map, empty, insertWith, toList)
import Data.Foldable
import Data.List
example_csv = "rest1,item1\nrest1,item2\nrest3,item1\nrest3,item2\nrest2,item3\nrest1,item5\nrest2,item2"
csvToDict :: String -> M.Map String [String]
csvToDict = foldToDict . map splitOnComma . lines
where
splitOnComma = words . map (\c -> if c == ',' then ' ' else c)
foldToDict = foldr (\[rest, item] -> M.insertWith (++) rest [item]) M.empty
main = do
let mapping = sort . M.toList . csvToDict $ example_csv
forM_ mapping $ \(rest, items) -> do
putStrLn rest
forM_ (sort items) $ \i -> putStrLn $ '\t' : i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment