【发布时间】:2014-09-18 15:07:56
【问题描述】:
我正在编写一个 haskell 程序,但遇到了 IO 类型的问题。我的 readLines 函数和它应该返回的类型似乎有问题。我希望它返回一个列表,其中每个元素都是使用 openDict 函数打开的文件中的一行。
这是我的代码。
main :: IO ()
main = do
fileHandle <- openDict
readLines fileHandle
putStr "End of program\n"
readLines :: Handle -> [IO String]
readLines fileHandle
| isEOF <- hIsEOF fileHandle = []
| otherwise = [hGetLine fileHandle] ++ readLines fileHandle
openDict :: IO Handle
openDict = do
putStr "Enter file path: "
filePath <- getLine
openFile filePath ReadMode
这是错误:
Couldn't match type `[]' with `IO'
Expected type: IO (IO String)
Actual type: [IO String]
In the return type of a call of `readLines'
In a stmt of a 'do' block: readLines fileHandle
In the expression:
do { fileHandle <- openDict;
readLines fileHandle;
putStr "End of program" }
所以基本上,我怎样才能将这些来自 IO 的字符串存储在一个列表中?
【问题讨论】:
-
[IO String]在这里没有多大意义。 (这并不是说它根本没有意义)。尝试使用IO [String]。 -
另外,
| isEOF <- hIsEOF fileHandle并不代表您认为的意思。它实际上并不检查 EOF,它只是 bindshIsEOF您应该稍后使用。这种语法对像 Maybe 这样的 monad 有意义,但对 IO 则不然。见paper。