懒惰的二进制得到

swi*_*ish 6 binary haskell lazy-evaluation

为什么Data.Binary.Get并不像它所说的那样懒惰?或者我在这里做错了什么?

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
Run Code Online (Sandbox Code Playgroud)

这个主要功能只是挂起而不是打印10个单词.

Mik*_*kov 4

您链接的文档提供了几个示例。第一个需要读取所有输入才能返回,并且看起来很像您编写的内容。第二个是左折叠,以流方式处理输入。这是用这种风格重写的代码:

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
Run Code Online (Sandbox Code Playgroud)

测试:

*Main> :main
[1,1,1,1,1,1,1,1,1,1]
Run Code Online (Sandbox Code Playgroud)