2012-07-12 45 views
1

我在弄清楚Haskell中的iteratee I/O是什麼。我用一些definitions檢查了以下Haskell-Wiki。瞭解Haskell中的iteratee函數

我不明白該函數的第二,第三和最後兩行的含義:

enumerator :: FilePath -> Iteratee (Maybe Char) o -> IO o 
enumerator file it = withFile file ReadMode 
    $ \h -> fix (\rc it -> case it of 
    Done o -> return o 
    Next f -> do 
     eof <- hIsEOF h 
     case eof of 
     False -> do 
      c <- hGetChar h 
      rc (f (Just c)) 
     True -> rc (f Nothing) 
    ) it 

我知道,iteratee功能做什麼,但我不明白一些行。 這個wikipage的其他功能真的很神祕。我不明白他們做什麼,因爲我想念一些解釋。

回答

4

您提到的這些行不是枚舉器/迭代器特定的,但我可以嘗試解釋它們。


withFile name mode = bracket (openFile name mode) (closeFile) 

換句話說,withFile打開一個文件,通過手柄爲給定的回調,並確保回調完成之後文件被關閉。


fix是一個定點組合器。例如,

fix (1 :) == 1 : 1 : 1 : 1 : ... 

它通常用於編寫自遞歸函數。 TFAE:

factorial 0 = 1 
factorial n = n * factorial (n-1) 

factorial n = fix (\f n -> case n of 0 -> 1; n -> n * f (n-1)) n 

我們可以重寫相同的功能沒有這些結構:

enumerator :: FilePath -> Iteratee (Maybe Char) o -> IO o 
enumerator file it = do 
    h <- openFile file ReadMode 
    let rc (Done o) = return o 
     rc (Next f) = do 
     eof <- hIsEof h 
     case eof of 
      False -> do 
      c <- hGetChar h 
      rc (f (Just c)) 
      True -> rc (f Nothing) 
    o <- rc it 
    closeFile h 
    return o 

雖然它並不完全準確,因爲withFile處理異常,這沒有。

這有幫助嗎?

2

也許這將有助於lambda函數的命名。

enumerator :: FilePath -> Iteratee (Maybe Char) o -> IO o 
enumerator file it = withFile file ReadMode $ stepIteratee it 
    where 
    stepIteratee (Done o) _h = return o 
    stepIteratee (Next f) h = do 
     eof <- hIsEOF h 
     case eof of 
     False -> do 
      c <- hGetChar h 
      stepIteratee (f (Just c)) h 
     True -> stepIteratee (f Nothing) h 

stepIteratee將繼續通過文件和iteratee兩個步進直到iteratee進入停止狀態。