- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当给定由\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/
我在 Haskell 中实现了 withFile: withFile' :: FilePath -> IOMode -> (Handle -> IO a) -> IO a withFile' pat
关注 haskell tutorial ,作者提供了以下实现 withFile 方法: withFile' :: FilePath -> IOMode -> (Handle -> IO a) -> I
当给定由\n 分隔的文本输入文件时,该程序会产生我期望的输出: import System.IO main :: IO () main = do h IO [String] getlines h =
在 iOS 12.1 中,unarchiveObject(withFile:) 已被弃用。 如何将 NSKeyedUnarchiver.unarchiveObject(withFile: String
我是 Laravel 新手, 如果 laravel 对输入文本进行验证 然后当验证失败时,它会返回输入的文本值 return Redirect::back()->withInput() larave
我是一名优秀的程序员,十分优秀!