当我在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]
谢谢!
答案 0 :(得分: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 ...
¹我不是百分之百确定,但经验支持它。