Lazy binary code

Why is Data.Binary.Get not lazy, as they say? Or am I doing something wrong here?

import Data.ByteString.Lazy (pack) import Data.Binary.Get (runGet, isEmpty, getWord8) getWords = do empty <- isEmpty if empty then return [] else do w <- getWord8 ws <- getWords return $ w:ws main = print $ take 10 $ runGet getWords $ pack $ repeat 1 

This main function just hangs instead of 10 words.

+6
source share
1 answer

The following documentation provides some examples. The first one has to read all the input data before it can return, and much resembles what you wrote. The second is the left key and processes input in a streaming manner. Here is your code rewritten in this style:

 module Main where import Data.Word (Word8) import qualified Data.ByteString.Lazy as BL import Data.Binary.Get (runGetState, getWord8) getWords :: BL.ByteString -> [Word8] getWords input | BL.null input = [] | otherwise = let (w, rest, _) = runGetState getWord8 input 0 in w : getWords rest main :: IO () main = print . take 10 . getWords . BL.pack . repeat $ 1 

Testing:

 *Main> :main [1,1,1,1,1,1,1,1,1,1] 
+4
source

All Articles