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?:
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)
CodePudding user response:
To match what you wrote for put
, you want pure Foo3B
there in get
.
CodePudding user response:
You can also derive these instances:
newtype Foo = Foo {value1 :: Int}
deriving newtype Binary
data Foo2 = Foo2A Int | Foo2B Int
deriving stock Generic
deriving anyclass Binary
data Foo3 = Foo3A Int | Foo3B
deriving stock Generic
deriving anyclass Binary