當您想將自定義型別轉換為位元組串時,您將執行以下操作:
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)
uj5u.com熱心網友回復:
您還可以派生這些實體:
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
uj5u.com熱心網友回復:
為了匹配您所寫的內容put,您希望pure Foo3B在get.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434058.html
標籤:哈斯克尔
上一篇:錯誤使用簡單的Haskell函式
