[Haskell-beginners] Signature of monadic functions

Chaddaï Fouché chaddai.fouche at gmail.com
Tue Oct 22 11:41:24 UTC 2013


Le 17 oct. 2013 12:57, "Daniel Trstenjak" <daniel.trstenjak at gmail.com> a
écrit :
>
>
> Hi Lorenzo,
>
> all the nice abstractions like Functor, Traversable or Foldable operate
> on the values of the Map. So there's 'Data.Traversable.mapM', which
> almost does what you want, but only for the values of the Map.
>
> Ok, here's a solution that does what you want:
>
> import Data.Map
> import Control.Monad
>
> mapKeysM :: (Ord k1, Ord k2, Monad m) => (k1 -> m k2) -> Map k1 v -> m
(Map k2 v)
> mapKeysM f map = return . fromList =<< mapM g (toList map)
>   where
>    g (key, value) = do
>       key' <- f key
>       return (key', value)
>

If you're worried that constructing the whole list then consuming it is too
much (use of mapM precludes a good streaming), you could use foldM to
construct the Map immediately, which would probably be exactly equivalent
to what mapKeys has to be doing (changing the keys obviously means
rebuilding the Map from scratch).

-- 
Chaddaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20131022/06b117ee/attachment.html>


More information about the Beginners mailing list