不确定此运行时错误的原因:
hdr or err: too few bytes
From: demandInput
来自以下内容:
module Main (main) where
import GHC.Word
import qualified Data.ByteString as BS
import Data.Serialize
import Data.Serialize.Get
import Data.Serialize.Put
data Header =
Header { ty :: Word8
, len :: Word16
} deriving (Show)
instance Serialize Header where
put (Header ty len) = do
putWord8 ty
putWord16be len
get = do
ty <- getWord8 >>= return . fromIntegral
len <- getWord16be >>= return . fromIntegral
return (Header ty len)
main :: IO ()
main = do
let bs = encode (Header 1 2)
let str = case (runGet get bs) of
Left err -> err
Right fr -> fr
putStrLn $ "hdr or err: " ++ str
答案 0 :(得分:3)
let str = case (runGet get bs) of
Left err -> err
Right fr -> fr
此处fr
的推断类型为String
,因为这是err
的类型,并且案例表达式的替代项必须具有相同的类型。因此,它使用Serialize
String
实例来解码结果,这显然不是您想要的。
要解决此问题,请首先添加show
以将解码结果转换为字符串,而不是强制将其作为字符串本身。然后,添加类型注释以解析现在不明确的fr
类型。
let str = case (runGet get bs) of
Left err -> err
Right fr -> show (fr :: Header)