Functor instance for a GADT with type constraint

后端 未结 1 2062
情书的邮戳
情书的邮戳 2020-12-16 21:17

Today I wanted to investigate if it is possible to construct a data type in such a way, that it does not store the data of the type of its type signature, but another repres

相关标签:
1条回答
  • 2020-12-16 21:53

    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.

    0 讨论(0)
提交回复
热议问题