0

不知道这个运行时错误的原因是什么:

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
4

1 回答 1

3
let str = case (runGet get bs) of
        Left err -> err
        Right fr -> fr

这里推断的类型frString,因为这是 的类型,err并且 case 表达式的替代项必须具有相同的类型。因此,它使用Serialize实例String来解码结果,这显然不是您想要的。

要解决此问题,首先添加show将解码结果转换为字符串,而不是将其强制为字符串本身。然后,添加一个类型注释来解决现在模棱两可的fr.

let str = case (runGet get bs) of
        Left err -> err
        Right fr -> show (fr :: Header)
于 2012-11-29T21:47:04.527 回答