codec icon indicating copy to clipboard operation
codec copied to clipboard

Monad instance for Codec'

Open Lysxia opened this issue 9 years ago • 3 comments

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 fw constraint).

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.

Lysxia avatar Oct 13 '16 11:10 Lysxia

This is very interesting! Are you sure that it follows the Monad laws though? Some examples would be great.

chpatrick avatar Oct 20 '16 16:10 chpatrick

Oops. I didn't mean to close it.

Lysxia avatar Oct 20 '16 17:10 Lysxia

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.

Lysxia avatar Oct 20 '16 17:10 Lysxia