将递归转为折叠?
Turn recursion to fold?
我编写了这段代码,它循环遍历文件句柄的行并对其执行任意操作。我认为它不需要递归 - 我可以将它变成折叠动作吗?
谢谢!
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
Haskell 非常避免手动处理句柄。它不能很好地与函数式编程风格一起使用。
对于像这样的简单输入处理器,最好的方法可能是只读取 整个文件 作为一个(惰性)字符串,然后处理其中的行:
processHandle h fn = mapM_ fn . lines =<< hgetContents h
当然这个也可以写成fold,查一下the definition of mapM_
.
现在,这种惰性 IO 方法不适用于许多严肃的应用程序。如果这不是一个巨大的文件,那么如果您严格阅读该文件可能会很好 with the Data.Text
equivalent. Else, if you really need to read lines interleaved with the processing steps, better look into conduit.
我编写了这段代码,它循环遍历文件句柄的行并对其执行任意操作。我认为它不需要递归 - 我可以将它变成折叠动作吗?
谢谢!
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
Haskell 非常避免手动处理句柄。它不能很好地与函数式编程风格一起使用。
对于像这样的简单输入处理器,最好的方法可能是只读取 整个文件 作为一个(惰性)字符串,然后处理其中的行:
processHandle h fn = mapM_ fn . lines =<< hgetContents h
当然这个也可以写成fold,查一下the definition of mapM_
.
现在,这种惰性 IO 方法不适用于许多严肃的应用程序。如果这不是一个巨大的文件,那么如果您严格阅读该文件可能会很好 with the Data.Text
equivalent. Else, if you really need to read lines interleaved with the processing steps, better look into conduit.