首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >理解Haskell中的iteratee函数

理解Haskell中的iteratee函数
EN

Stack Overflow用户
提问于 2012-07-13 06:51:20
回答 2查看 223关注 0票数 1

我正在尝试弄清楚什么是Haskell中的迭代式I/O。我用一些definitions检查了下面的Haskell-Wiki。

我不理解该函数的第二行、第三行和最后两行的含义:

代码语言:javascript
运行
复制
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上的其他功能真的很神秘。我不明白他们是做什么的,因为我错过了一些解释。

EN

回答 2

Stack Overflow用户

发布于 2012-07-13 09:07:15

您提到的行并不是特定于枚举器/迭代器的,尽管我可以尝试解释它们。

代码语言:javascript
运行
复制
withFile name mode = bracket (openFile name mode) (closeFile)

换句话说,withFile打开一个文件,将句柄传递给给定的回调,并确保在回调完成后关闭该文件。

fix是一个定点组合器。例如,

代码语言:javascript
运行
复制
fix (1 :) == 1 : 1 : 1 : 1 : ...

它通常用于编写自递归函数。TFAE:

代码语言:javascript
运行
复制
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

我们可以在没有这些构造的情况下重写相同的函数:

代码语言:javascript
运行
复制
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处理异常,而这不是。

这有帮助吗?

票数 4
EN

Stack Overflow用户

发布于 2012-07-13 14:56:21

如果将lambda函数命名,可能会有所帮助。

代码语言:javascript
运行
复制
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将继续遍历文件和迭代器,直到迭代器停止。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11461875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档