3

尝试使用 Data.Binary.Get 和 ByteString 却不明白发生了什么。我的代码如下:

getSegmentParams :: Get (Int, L.ByteString)
getSegmentParams = do 
    seglen <- liftM fromIntegral getWord16be
    params <- getByteString (seglen - 2)
    return (seglen, params)

对于返回元组的第三项,即有效负载,我收到以下错误:

Couldn't match expected type `L.ByteString'
       against inferred type `bytestring-0.9.1.4:Data.ByteString.Internal.ByteString'

有人请向我解释 Data.Binary.Get 和 ByteStrings 之间的交互以及我如何做我想做的事情。谢谢。

4

2 回答 2

5

It says you expect the second element of the tuple to be a L.ByteString (I assume that L is from Data.ByteString.Lazy) but the getByteString routine returns a strict ByteString from Data.ByteString. You probably want to use getLazyByteString.

于 2010-03-10T00:10:45.867 回答
1

There are two ByteString data types: one is in Data.ByteString.Lazy and one is in Data.ByteString.

Given the L qualifying your ByteString, I presume you want the lazy variety, but getByteString is giving you a strict ByteString.

Lazy ByteStrings are internally represented by a list of strict ByteStrings.

Fortunately Data.ByteString.Lazy gives you a mechanism for turning a list of strict ByteStrings into a lazy ByteString.

If you define

import qualified Data.ByteString as S


strictToLazy :: S.ByteString -> L.ByteString
strictToLazy = L.fromChunks . return 

you can change your code fragment to

getSegmentParams :: Get (Int, L.ByteString)
getSegmentParams = do 
    seglen <- liftM fromIntegral getWord16be
    params <- getByteString (seglen - 2)
    return (seglen, strictToLazy params)

and all should be right with the world.

于 2010-03-10T00:10:13.650 回答