【问题标题】:Read a list of integers lazily as a bytestring懒惰地读取整数列表作为字节串
【发布时间】:2015-07-27 22:16:28
【问题描述】:

我正在尝试查找文件中整数的总和。使用普通字符串的代码是:

main = do
  contents <- getContents
  L.putStrLn (sumFile contents)
  where sumFile = sum . map  read. words

我尝试将其更改为使用 Data.ByteString.Lazy 模块,如下所示:

import Data.ByteString.Lazy as L

main = do
  contents <- L.getContents
  L.putStrLn (sumFile contents)
  where sumFile = sum . L.map  read. words

但这拒绝了,因为 words 返回了一个字符串。然后我尝试使用Data.ByteString.Char8,但它使用了严格的字节字符串。

我怎样才能使这个函数完全惰性?

【问题讨论】:

  • Data.ByteString.Lazy.Char8?
  • 如果您确定编码是 latin1,那么您可以使用 @melpomene 指出的懒惰的Char8 模块。否则,Data.Text.Lazy 也可以与其他编码一起使用。

标签: haskell lazy-evaluation bytestring


【解决方案1】:

我找到了一个稍微长一点的解决方法,将文件作为 ByteString 读取,然后作为整数列表读取。感谢@melpomene

import Data.ByteString.Lazy.Char8 as L
main = do
    contents <- L.getContents
    print (sumFile contents)
         where sumFile x = sum $ Prelude.map tups $ Prelude.map L.readInt (L.words x)
             where read' = tups.(L.readInt)


tups :: (Num a) => (Maybe (a, b)) -> a
tups (Just (a,b)) = a
tups Nothing = 0

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2015-04-24
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2013-05-24
    • 2022-01-11
    相关资源
    最近更新 更多