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

Anatoly Zaretsky anatoly.zaretsky at gmail.com
Wed Dec 28 13:55:11 UTC 2016


On Wed, Dec 28, 2016 at 9:28 AM, Cody Goodman <codygman.consulting at gmail.com
> wrote:

> My goal is to take data like this:
>
>                         [ Info 0 "Alcohol" "TX"
>                         , Info 1 "Alcohol" "TX"
>                         , Info 2 "Pregnancy" "MA"
>                         ]
>
> and build a Map like this:
>
> [("MA",[("Pregnancy",1)]),("TX",[("Alcohol",2)])]
>

You can convert each individual record to a singleton map:

wrapRecord :: Info -> M.Map String (M.Map String Integer)
wrapRecord (Info _ state healthTopic) = M.singleton state (M.singleton
healthTopic 1)

and then union all these singletons:

numTopicsPerState = M.unionsWith (M.unionWith (+)) . map wrapRecord $ [Info
0 "Alcohol" "TX", Info 1 "Alcohol" "TX", Info 2 "Pregnancy" "MA"]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20161228/ea3d32d4/attachment.html>


More information about the Haskell-Cafe mailing list