简单的Data.Serialize“太少的字节”

时间:2012-11-29 21:20:16

标签: haskell

不确定此运行时错误的原因:

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

1 个答案:

答案 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)