它不是懒惰的,因为Get
monad 是一个严格的状态 monad(在binary-0.5.0.2 到 0.5.1.1;它以前是一个懒惰的状态 monad,在binary-0.6.*中它已成为一个延续 monad,我没有分析了该更改的严格性含义):
-- | The parse state
data S = S {-# UNPACK #-} !B.ByteString -- current chunk
L.ByteString -- the rest of the input
{-# UNPACK #-} !Int64 -- bytes read
-- | The Get monad is just a State monad carrying around the input ByteString
-- We treat it as a strict state monad.
newtype Get a = Get { unGet :: S -> (# a, S #) }
-- Definition directly from Control.Monad.State.Strict
instance Monad Get where
return a = Get $ \s -> (# a, s #)
{-# INLINE return #-}
m >>= k = Get $ \s -> case unGet m s of
(# a, s' #) -> unGet (k a) s'
{-# INLINE (>>=) #-}
因此最终的递归
get >>= \x ->
get >>= \(Stream xs) ->
return (Stream (x:xs))
Stream
强制在返回之前读取整个内容。
我认为不可能Stream
在Get
单子中懒惰地解码 a (所以更不用说Binary
实例了)。但是您可以使用以下方法编写惰性解码函数runGetState
:
-- | Run the Get monad applies a 'get'-based parser on the input
-- ByteString. Additional to the result of get it returns the number of
-- consumed bytes and the rest of the input.
runGetState :: Get a -> L.ByteString -> Int64 -> (a, L.ByteString, Int64)
runGetState m str off =
case unGet m (mkState str off) of
(# a, ~(S s ss newOff) #) -> (a, s `join` ss, newOff)
首先编写一个Get
返回 a 的解析器Maybe a
,
getMaybe :: Binary a => Get (Maybe a)
getMaybe = do
t <- getWord8
case t of
0 -> return Nothing
_ -> fmap Just get
然后用它来制作一个类型的函数(ByteString,Int64) -> Maybe (a,(ByteString,Int64))
:
step :: Binary a => (ByteString,Int64) -> Maybe (a,(ByteString,Int64))
step (xs,offset) = case runGetState getMaybe xs offset of
(Just v, ys, newOffset) -> Just (v,(ys,newOffset))
_ -> Nothing
然后你可以Data.List.unfoldr
用来懒惰地解码一个列表,
lazyDecodeList :: Binary a => ByteString -> [a]
lazyDecodeList xs = unfoldr step (xs,0)
并将其包装在一个Stream
lazyDecodeStream :: Binary a => ByteString -> Stream a
lazyDecodeStream = Stream . lazyDecodeList