将自定义数据类型编码为惰性字节字符串

Encode Custom Data Type to Lazy Byte String

当您想将自定义类型转换为字节串时,您可以执行以下操作:

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

如果您有一个具有多个可行值的类型:

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

但是如果你有这样的类型(以下...)我该怎么做?:

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)

为了匹配您为 put 编写的内容,您需要 pure Foo3Bget 中。

您还可以导出这些实例:

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