[Haskell-beginners] Adapting code from an imperative loop

Bob Ippolito bob at redivi.com
Fri Jun 19 06:18:45 UTC 2015


On Friday, June 19, 2015, Matt Williams <matt.williams45.mw at gmail.com>
wrote:

> Dear All,
>
> I have been wrestling with this for a while now.
>
> I have a list of data items, and want to be able to access them, in a Hash
> Map, via a short summary of their characteristics.
>
> In an imperative language this might look like:
>
> myMap = new map()
> for elem in myElems:
>     key = makeKey(elem)
>     myMap[key] = myMap[key] + elem
>
> I have been trying to do this in Haskell, but am stuck on how to hand the
> Map back to itself each time.
>
> I have a function :: elem -> [p,q] to make the key, but the Map.insert
> function has the following signature:
>
> insert :: (Hashable
> <https://hackage.haskell.org/package/hashmap-1.0.0.2/docs/Data-Hashable.html#t:Hashable>
>  k, Ord
> <https://hackage.haskell.org/packages/archive/base/4.2.0.2/doc/html/Data-Ord.html#t:Ord> k)
> => k -> a -> HashMap
> <https://hackage.haskell.org/package/hashmap-1.0.0.2/docs/Data-HashMap.html#t:HashMap> k
> a -> HashMap
> <https://hackage.haskell.org/package/hashmap-1.0.0.2/docs/Data-HashMap.html#t:HashMap> k
> a
>
> My thought was that I needed to go through the list of the elems, and at
> each point add them to the Hash Map, handing the updated Map onto the next
> step - but this is what I cannot write.
>

This is typically done with fromListWith or a combination of foldl' and
insertWith or alter.

-bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150619/6b295672/attachment.html>


More information about the Beginners mailing list