Not sure how reason about this run-time error:
hdr or err: too few bytes
From: demandInput
from the following:
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
The inferred type of
frhere isString, since that’s the type oferrand the alternatives of a case expression must have the same type. Therefore, it’s using theSerializeinstance forStringto decode the result, which is obviously not what you intended.To fix this, first add
showto convert the decoded result to a string instead of forcing it to be a string itself. Then, add a type annotation to resolve the now-ambiguous type offr.