Search code examples
haskelltextdictionarytraversalbytestring

Are there monadic/applicative map (i.e. traverse/mapM) functions over ByteString or Text?


There are standard (pure) map functions for ByteString and Text:

map :: (Word8 -> Word8) -> ByteString -> ByteString
map :: (Char -> Char) -> Text -> Text

but I'm missing their monadic/applicative counterparts:

traverse :: (Applicative f) => (Word8 -> f Word8) -> ByteString -> f ByteString
traverse :: (Applicative f) => (Char -> f Char) -> Text -> f Text

(If we have traverse we can define mapM f = unwrapMonad . traverse (WrapMonad . f).)

I tried looking through the packages, tried Hoogle, but I didn't find them. Did I overlook something? Or is there a reason why they're missing (like it's not possible/easy to define them efficiently)?


Solution

  • Incidentally, you have exactly what you need in Edward Kmett's lens package; your desired traverse versions are simply Data.Bytestring.Lens.bytes and Data.Text.Lens.text.

    Edit: To clarify, the above-mentioned functions are of (a generalization of) type SimpleTraversal c e (for (c ~ Bytestring, e ~ Word8) and (c ~ Text, e ~ Char), respectively), which is a type synonym for forall f. (Applicative f) => (e -> f e) -> c -> f c