codec
codec copied to clipboard
Generic construction of codecs
Using Generic its easy to combine multiple codecs into more complex ones. This is especially useful for sum types, which were previously hard to deal with when constructing codecs. It is for example possible to write functions for lists and Maybe:
many' :: (Alternative r, Applicative w) => Codec r w a -> Codec r w [a]
many' c = match $ pure () `rchoose` (c `combine` many' c)
maybe' :: (Alternative r, Applicative w) => Codec r w () -> Codec r w a -> Codec r w (Maybe a)
maybe' n j = match $ n `rchoose` j
I think sum types are so hard to deal with because you have to "prove" to the compiler, that you covered all possible cases when serializing. These changes solve this problem by using Generic to deconstruct any type into a combination of tuples and Either.
Another solution would be to write a Alternative instance, but this would require w to also have an Alternative instance, which is generally not the case.