[Haskell-cafe] Multi groupby with foldl' and Map.insertWithKey

ALeX Kazik alex at kazik.de
Wed Dec 28 07:54:41 UTC 2016

> My goal is to take data like this:
> and build a Map like this:

you do not want to insert into the map but alter instead:

numTopicsPerState :: M.Map String (M.Map String Integer)
numTopicsPerState = foldl' addState M.empty
                        [ Info 0 "Alcohol" "TX"
                        , Info 1 "Alcohol" "TX"
                        , Info 2 "Pregnancy" "MA"
    addState accum currentRow = M.alter addTopic (state currentRow) accum
        addTopic accum = Just $ M.alter incCount (healthTopic
currentRow) (fromMaybe M.empty accum)
        incCount oldCount = Just $ 1 + fromMaybe 0 oldCount

More information about the Haskell-Cafe mailing list