Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Encode Custom Data Type to Lazy Byte String

when you want to convert a custom type into bytestring you would do following:

data Foo = Foo {value1 :: Int}
instance Binary Foo where
   get =liftM Foo get
   put b = put (value1 b)

and if you have a type with multiple viable values as such:

data Foo2 = Foo2A Int | Foo2B Int 
instance Binary Foo2 where
   get = do flag <- getWord8
         case flag of 
               0 -> fmap Foo2A get
               1 -> fmap Foo2B get
   put (Foo2A i) = do put (0 :: Word8) 
                      put i
   put (Foo2B i) = do put (1 :: Word8)
                      put i

but if you have a type as such (following…) how would I do this?:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data Foo3 = Foo3A Int | Foo3B
instance Binary Foo3 where
   get = do flag <- getWord8
            case flag of
                 0 -> fmap Foo3A get
                 1 -> ....????? Foo3B has no value - only Data Constructor
   put (Foo3A i) = do put (0 :: Word8)
                      put i
   put (Foo3B)   = put (1 :: Word8)

>Solution :

To match what you wrote for put, you want pure Foo3B there in get.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading