gpt4 book ai didi

haskell - Haskell 中的泛型序列化

转载 作者:行者123 更新时间:2023-12-04 15:46:24 26 4
gpt4 key购买 nike

当我尝试反序列化对象时出现此错误。

Amy64.hs: GetException "too few bytes\nFrom:\tdemandInput\n\n"

输出文件已创建,如下所示:
00000000  1f 8b 08 00 00 00 00 00  04 03 63 60 00 03 56 a7  |..........c`..V.|
00000010 d2 f4 e2 4a 00 be b2 38 41 0d 00 00 00 |...J...8A....|

我怀疑我错误地使用了新的泛型。这是我的代码。顺便说一句,如果我删除第 9、22 和 23 行,我会得到相同的结果。如果我删除 gzip/ungzip 的东西,我会得到相同的结果。
{-# LANGUAGE DeriveGeneric #-}

import Data.Conduit (runResourceT, ($$), (=$))
import Data.Conduit.Binary (sinkFile, sourceFile)
import Data.Conduit.Cereal (sinkGet, sourcePut)
import Data.Conduit.Zlib (gzip, ungzip)
import qualified Data.Serialize as DS (Serialize, get, put)
import GHC.Generics (Generic)
import Data.Serialize.Derive (derivePut, deriveGet) -- line 9

readBug :: FilePath -> IO (Either String Bug)
readBug f =
runResourceT $ sourceFile f $$ ungzip =$ sinkGet (DS.get)

writeBug :: FilePath -> Bug -> IO ()
writeBug f t =
runResourceT $ sourcePut (DS.put t) $$ gzip =$ sinkFile f

data Bug = Bug String deriving (Show, Generic)

instance DS.Serialize Bug where
put = derivePut -- line 22
get = deriveGet -- line 23

main = do
let a = Bug "Bugsy"
writeBug "x.dat" a
(Right b) <- readBug "x.dat" :: IO (Either String Bug)
print b

最佳答案

事实证明,我的错误与泛型本身无关。 readBug 上的类型签名错误函数导致它尝试读取 Either String Bug而不仅仅是 Bug .

{-# LANGUAGE DeriveGeneric #-}

import Data.Conduit (runResourceT, ($$), (=$))
import Data.Conduit.Binary (sinkFile, sourceFile)
import Data.Conduit.Cereal (sinkGet, sourcePut)
import Data.Conduit.Zlib (gzip, ungzip)
import qualified Data.Serialize as DS (Serialize, get, put)
import GHC.Generics (Generic)
import Data.Serialize.Derive (derivePut, deriveGet) -- line 9

readBug :: FilePath -> IO Bug
readBug f =
runResourceT $ sourceFile f $$ ungzip =$ sinkGet DS.get

writeBug :: FilePath -> Bug -> IO ()
writeBug f t =
runResourceT $ sourcePut (DS.put t) $$ gzip =$ sinkFile f

data Bug = Bug String deriving (Show, Generic)

instance DS.Serialize Bug where
put = derivePut -- line 22
get = deriveGet -- line 23

main :: IO ()
main = do
let a = Bug "Bugsy"
writeBug "x.dat" a
b <- readBug "x.dat" :: IO Bug
print b

关于haskell - Haskell 中的泛型序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12935246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com