Functor instance for a GADT with type constraint

ぃ、小莉子 提交于 2019-11-29 04:13:35

You can do this using a CoYoneda functor.

The idea is simple: have an additional functional field where you accumulate your fmaping functions. When you decode your value, then apply that function.

Here's the code:

{-# LANGUAGE GADTs #-}
import Data.ByteString.Char8
import Data.Serialize

data Serialized a where
    MkSerialized
      :: (Serialize a)
      => ByteString -> (a -> b) -> Serialized b

decode' :: Serialized a -> a
decode' (MkSerialized bs f) = let Right r = decode bs in f r

instance Functor Serialized where
    fmap f (MkSerialized bs g) = MkSerialized bs (f . g)

This also has the benefit of automatically fusing multiple fmaps instead of repeated decodings and encodings, as would be in your case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!