List Haskell IO-要列出的文件行
我正在编写一个haskell程序,在IO类型方面遇到了问题。我的readLines函数和它应该返回的类型似乎有问题。我希望它返回一个列表,其中每个元素都是使用openDict函数打开的文件中的一行List Haskell IO-要列出的文件行,list,haskell,io,List,Haskell,Io,我正在编写一个haskell程序,在IO类型方面遇到了问题。我的readLines函数和它应该返回的类型似乎有问题。我希望它返回一个列表,其中每个元素都是使用openDict函数打开的文件中的一行 import Control.Applicative readLines3 :: Handle -> IO [String] readLines3 fileHandle = lines <$> hGetContents fileHandle 这是我的密码 main :: IO ()
import Control.Applicative
readLines3 :: Handle -> IO [String]
readLines3 fileHandle = lines <$> hGetContents fileHandle
这是我的密码
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
main::IO()
main=do
文件句柄[IO字符串]
readLines文件句柄
|isEOF这是您可能真正想要的阅读行
readLines :: Handle -> IO [String]
readLines h = do
isEOF <- hIsEOF h -- need to access isEOF directly, without monad, see comment about the bind
case isEOF of
True -> return [] -- the return adds the IO monad to the [String] type
False -> do
line <- hGetLine h -- need to access line separately without monad
lines <- readLines h -- recurse down
return $ line ++ lines -- return adds back the IO monad
readLines::Handle->IO[字符串]
读线h=do
isEOF return[]——返回将IO单子添加到[String]类型
False->do
line您的readLines
函数有几个问题
首先,在这种情况下,您不希望返回[IO字符串]
。这是一个IO操作列表,例如[print 1>>返回“a”,print 2>>返回“b”]
,这不是您想要的。您需要一个IO操作返回String
s列表,因此需要使用IO[String]
第二,IO[String]的模式guardISEO
readLines3 fileHandle=行hGetContents fileHandle
[IO字符串]
在这里没有什么意义。(这并不是说这毫无意义)。尝试使用IO[String]
。另外|非常感谢您解释了我代码中的错误以及修复错误的方法。我已决定选择库函数作为解决方案。
readLines :: Handle -> IO [String]
readLines fileHandle = do
eof <- hIsEOF fileHandle
if eof then return []
else do line <- hGetLine fileHandle
rest <- readLines fileHandle
return (line:rest)
import Control.Applicative
readLines2 :: Handle -> IO [String]
readLines2 fileHandle = do
eof <- hIsEOF fileHandle
if eof then return []
else (:) <$> hGetLine fileHandle <*> readLines2 fileHandle
import Control.Applicative
readLines3 :: Handle -> IO [String]
readLines3 fileHandle = lines <$> hGetContents fileHandle