1

当我在 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
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]

谢谢!

4

1 回答 1

3
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% 确定这一点,但经验支持它。

于 2012-08-30T20:35:16.450 回答