代码之家  ›  专栏  ›  技术社区  ›  Carbon

将递归转换为折叠?

  •  1
  • Carbon  · 技术社区  · 8 年前

    我编写的代码循环遍历文件句柄的行,并对其执行任意操作。我不认为它应该是递归的——我能把它变成折叠动作吗?

    谢谢

    processHandle :: Handle -> (String->IO ()) -> IO ()
    processHandle h fn = do
                       eof <- hIsEOF h
                       if eof then
                         return ()
                        else do
                          myLine <- hGetLine h
                          fn myLine
                          processHandle h fn
    
    1 回复  |  直到 8 年前
        1
  •  6
  •   leftaroundabout    8 年前

    Haskell非常避免手动操作手柄。它与函数式编程风格配合不好。

    对于这样一个简单的输入处理器,最好只读取 整个文件

    processHandle h fn = mapM_ fn . lines =<< hgetContents h
    

    当然,这也可以写成折叠,只要抬头看 the definition of mapM_ .

    现在,这种懒惰的IO方法对于许多严肃的应用程序来说并不适用。如果这不是一个大文件,那么只要严格阅读该文件就可以了 with the Data.Text equivalent 。否则,如果您真的需要读取与处理步骤交错的行,最好查看 conduit .