我正在尝试弄清楚什么是Haskell中的迭代式I/O。我用一些definitions检查了下面的Haskell-Wiki。
我不理解该函数的第二行、第三行和最后两行的含义:
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上的其他功能真的很神秘。我不明白他们是做什么的,因为我错过了一些解释。
发布于 2012-07-13 09:07:15
您提到的行并不是特定于枚举器/迭代器的,尽管我可以尝试解释它们。
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处理异常,而这不是。
这有帮助吗?
发布于 2012-07-13 14:56:21
如果将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) hstepIteratee将继续遍历文件和迭代器,直到迭代器停止。
https://stackoverflow.com/questions/11461875
复制相似问题