【问题标题】:Lazy ByteString strange behaviour or bug?懒惰的 ByteString 奇怪的行为或错误?
【发布时间】:2012-08-25 15:36:35
【问题描述】:

当我在 GHCI 中测试我的函数 intervalFinder 时,它似乎正在工作,但是当我尝试编译它时,我没有输出:

函数作用于输入:

*Main> intervalFinder $[B.pack"first",B.pack"second",B.empty,B.pack"third",B.emp
ty]
Loading package bytestring-0.9.2.1 ... linking ... done.
["Start Time: first","End   Time: second","Start Time: third","End   Time: third
"]

并运行 main:

*Main> main
Loading package bytestring-0.9.2.1 ... linking ... done.
*Main> :q
Leaving GHCi.

在 results.txt 中打印:

Start Time: firstEnd   Time: secondStart Time: thirdEnd   Time: third 

但如果我运行 ghc test3.hs,输出文件为 0kb(显然其中没有数据!)

我做错了吗?

代码:

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as Bl
import System.IO 
import System.Environment


intervalFinder :: [B.ByteString]->[B.ByteString]
intervalFinder x = helper x ""
    where
    helper (x:xs) "" 
        | x /= ""   = ((B.append (B.pack("Start Time: ")) x)):(helper xs x)
        | otherwise = helper xs ""
    helper (x:xs) y
        | x == ""   = ( (B.append (B.pack("End   Time: ")) y)):(helper xs "")
        | otherwise = helper xs x
    helper _ _      = []

main = do
    filehandle <- openFile "result.txt" WriteMode
    Bl.hPutStr (filehandle) .  Bl.fromChunks . intervalFinder $[B.pack"first",B.pack"second",B.empty,B.pack"third",B.empty]

谢谢!

【问题讨论】:

    标签: haskell bytestring


    【解决方案1】:
    main = do
        filehandle <- openFile "result.txt" WriteMode
        Bl.hPutStr (filehandle) .  Bl.fromChunks . intervalFinder
              $[B.pack"first",B.pack"second",B.empty,B.pack"third",B.empty]
    

    输出是缓冲的,因此程序退出时不会使用runghc 或已编译的二进制文件刷新缓冲区。在 ghci 中,退出 ghci 时会刷新所有缓冲区¹。

    当你openFile一个文件句柄时,你应该在使用后hClose它。如果输出缓冲区以写入或追加模式打开,这也会刷新输出缓冲区。

    main = do
        filehandle <- openFile "result.txt" WriteMode
        Bl.hPutStr (filehandle) .  Bl.fromChunks . intervalFinder
              $[B.pack"first",B.pack"second",B.empty,B.pack"third",B.empty]
        hClose filehandle
    

    或者,您可以使用writeFile

    main = Bl.writeFile "result.txt" $ Bl.fromChunks ...
    

    ¹我不能 100% 确定这一点,但经验支持它。

    【讨论】:

    • 成功了!我被卡住了,因为在插入 inverfalFinder 之前,代码工作正常(我有 map (Bl.pack . B.unpack))并且无法弄清楚为什么一个工作而另一个没有。
    • hClose 代码不安全(如果出现异常,可能会泄漏句柄)。这就是withFile 的用途。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 2012-11-26
    • 2015-07-27
    • 2015-09-06
    相关资源
    最近更新 更多