Proposal: Non-allocating way to iterate over a Data.Map: traverseWithKey_

Henning Thielemann lemming at
Tue Jul 2 20:45:49 CEST 2013

On Tue, 2 Jul 2013, Ryan Newton wrote:

> If there's not an existing way to do this, I suppose this is a minor proposal.
> When writing monadic code that consumes a container (Set, Map) etc, I often find that I just want what
> iterators in imperative languages provide:  that is, to iterate over the contents of a large container,
> performing monadic effects along the way, but without allocating.
> The Foldable instance for Data.Map almost gives you what you want, but it only exposes the values, not their
> keys.  The "traverseWithKey" function is close too, but it builds a new Map as output:
> traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b)
> So in practice what I do, and what I assume others do is this:
> mapM_ f (toList myMap)

You could also do

   Map.foldrWithKey (\k a -> f k a >>) (return ())

which does not need an interim Map, or

   Foldable.sequence_ . Map.mapWithKey f

which looks more elegant.

More information about the Libraries mailing list