我正在尝试在文件中找到整数之和。使用普通字符串的代码是:
>>> re.findall("(.{0,5}searchstring.{0,5})", text)
['searchstring12345', '12searchstring12', '34567searchstring12345']
我尝试将其更改为使用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
,但它使用了严格的ByteString。
如何让这个功能完全懒惰?
答案 0 :(得分: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