purescript-codec icon indicating copy to clipboard operation
purescript-codec copied to clipboard

Why is `Codec` a type rather than a type class?

Open alphashuro opened this issue 1 year ago • 2 comments

I have been learning Purescript recently and I have a question if you have some time to entertain me 😅

I was implementing a toy project and before I discovered this package, I created a type class that served as a Codec definition, defining encode and decode functions.

class Codec a b e where
  encode :: a -> b
  decode :: b -> Either e a

I then create an instance of this Codec for each of the types in my domain.

Comparing my implementation to yours, I'm curious about why Codec is implemented as a type in this module rather than a type class?

PS: I know this is probably not the right place for this, let me know if there is a better place to ask such questions.

alphashuro avatar Jul 04 '24 18:07 alphashuro

The short answer is: you can only have one instance for a type when using typeclasses, and the drawbacks of that become apparent quite quickly if you're not in complete control of the serialization format.

I wrote some stuff about it a while back, before these codec-based libraries existed.

garyb avatar Jul 04 '24 22:07 garyb