gpt4 book ai didi

haskell - withFile 与 openFile

转载 作者:行者123 更新时间:2023-12-02 05:26:06 32 4
gpt4 key购买 nike

当给定由\n 分隔的文本输入文件时,该程序会产生我期望的输出:

import System.IO

main :: IO ()
main = do h <- openFile "test.txt" ReadMode
xs <- getlines h
sequence_ $ map putStrLn xs

getlines :: Handle -> IO [String]
getlines h = hGetContents h >>= return . lines

用 withFile 替换 openFile 并稍微重新排列

import System.IO

main :: IO ()
main = do xs <- withFile "test.txt" ReadMode getlines
sequence_ $ map putStrLn xs

getlines :: Handle -> IO [String]
getlines h = hGetContents h >>= return . lines

我根本没有得到任何输出。我被难住了。

编辑:不再被难住了:感谢所有人深思熟虑且发人深省的答案。我又阅读了一些文档,了解到 withFile 可以理解为 bracket 的部分应用。

这就是我最终得到的结果:

import System.IO

main :: IO ()
main = withFile "test.txt" ReadMode $ \h -> getlines h >>= mapM_ putStrLn

getlines :: Handle -> IO [String]
getlines h = lines `fmap` hGetContents h

最佳答案

文件关闭得太早。来自 documentation :

The handle will be closed on exit from withFile

这意味着 withFile 函数返回后文件将立即关闭。

因为 hGetContents 和 friend 很懒,它不会尝试读取文件,直到用 putStrLn 强制它,但到那时,withFile 已经关闭了该文件。

要解决该问题,请将整个内容传递给 withFile:

main = withFile "test.txt" ReadMode $ \handle -> do
xs <- getlines handle
sequence_ $ map putStrLn xs

这是有效的,因为当 withFile 开始关闭文件时,您已经打印了它。

关于haskell - withFile 与 openFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9406463/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com