2012-08-30 68 views
1

當我在GHCI測試我的功能intervalFinder它似乎是工作,但是當我嘗試編譯它,我沒有輸出:Lazy ByteString奇怪的行爲或錯誤?

該功能適用​​於輸入:

*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 
"] 

而且在RESULTS.TXT

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

打印:運行主

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] 

謝謝!

回答

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退出1時,所有緩衝區都將被刷新。

當你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%,但經驗支持它。

+0

這個技巧! 我被卡住了,因爲在插入inverfalFinder之前,代碼工作正常(我有地圖(Bl.pack。B.unpack)),無法弄清楚爲什麼一個人工作而另一個沒有。 – MdxBhmt

+1

'hClose'代碼是不安全的(在例外的情況下可能會泄漏該句柄)。這就是'withFile'的用途。 – Peaker