codec
codec copied to clipboard
Monad instance for Codec'
This builds on top of PR #4 to use Codec' as a Monad.
This allows to parse formats that are prefixed with some metadata that determines the rest of the encoding. For instance, a bytestring can be encoded with its length first:
byteStringCodec
:: Codec fr fw Int -- Length
-> (Int -> Codec fr fw ByteString) -- A bytestring of fixed length
-> Codec fr fw ByteString
byteStringCodec codecLength codecBS = do
n <- BS.length =. codecLength
codecBS n
I have put this in a separate PR because it is a breaking change.
Codec'has a slightly different definition;- some functions have more constrained types (a
Functor fwconstraint).
While #4 is not strictly required for the instance, the ability to (co)map over the w parameter is crucial to make that instance usable.
If you are interested in merging this, I can write some documentation about how to use write monadic Codecs before that happens.
This is very interesting! Are you sure that it follows the Monad laws though? Some examples would be great.
Oops. I didn't mean to close it.
Codec' fr fw w r is isomorphic to Product get (ReaderT w put) r (Product from Data.Functor.Product) so I'm quite sure it is actually a monad. I'll think of more examples.