mapM_ for bytestring

Artyom Kazak yom at artyom.me
Sun Sep 1 13:31:00 CEST 2013


On Sun, 01 Sep 2013 15:18:32 +0400, Erik de Castro Lopo  
<mle+hs at mega-nerd.com> wrote:

> Err, mapM is defined as:
>
>     mapM :: Monad m => (a -> m b) -> [a] -> m [b]

Yeah, the signatures for mapM_ and mapM would respectively be

     mapM_ :: Monad m => (Word8 -> m b)     -> ByteString -> m ()
     mapM  :: Monad m => (Word8 -> m Word8) -> ByteString -> m ByteString

After all, the signature for ByteString-y `map` too requires a function
of type `Word8 -> Word8`, so it seems perfectly reasonable for mapM to  
exist.

> in that the second parameter is a list. ByteStrings are not lists,
> they're chunks of bytes. Besides, you can just do:
>
>    let bs = "This is a bytestring"
>     mapM someFUnctions $ BS.unpack bs
>
> or define a function:
>
>     mapBSM :: Monad m => (Char -> m a) -> ByteString -> m [a]
>     mapBSM f bs = mapM f $ BS.unpack bs
>
> and similar for mapBSM_.

There’s even a RULE which would optimise this. However, it still would be
*four times slower* than necessary if the monad in question is IO or ST.




More information about the Libraries mailing list