Skip to content

Conversation

@MDeiml
Copy link

@MDeiml MDeiml commented Dec 12, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant