使用Data.Binary对列表进行延迟解码

时间:2012-07-27 20:41:49

标签: haskell lazy-evaluation

我懒惰地使用此代码编码列表(取自此SO question):

import Data.Binary

newtype Stream a = Stream { unstream :: [a] }

instance Binary a => Binary (Stream a) where

    put (Stream [])     = putWord8 0
    put (Stream (x:xs)) = putWord8 1 >> put x >> put (Stream xs)

问题是解码实现不是懒惰的:

    get = do
        t <- getWord8
        case t of
            0 -> return (Stream [])
            1 -> do x         <- get
                    Stream xs <- get
                    return (Stream (x:xs))

这让我觉得它应该是懒惰的,但是如果我们运行这个测试代码:

head $ unstream (decode $ encode $ Stream [1..10000000::Integer] :: Stream Integer)

内存使用量爆炸。出于某种原因,在让我查看第一个元素之前,它想要解码整个列表。

为什么这不是懒惰,我怎么能让它变得懒惰?

1 个答案:

答案 0 :(得分:6)

它不是懒惰的,因为Get monad是一个严格的状态monad(在binary-0.5.0.2 to 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 monad中的Get是不可能的(所以更不用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解析器,返回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