好的,首先,
IO ==> System.IO
接下来让我们看看 readLines(PS readFile 在这里可以很好地工作)
readLines :: Handle -> [String] -> [String] --You have to return an IO [String] here.
readLines handler list = do
eof <- hIsEOF handler
if eof then return list --Return an IO list
else do
line <- hGetLine handler
readLines handler (list ++ [line])
接下来writeLines
(PSwriteFile
也会有帮助)
writeLines :: Handle -> [String] -> [String] -- You have to return IO of something, I'd recommend ().
writeLines handler list = if length list == 0
then list --Change to return ()
else do
line <- head list --Should be let here. Like let line = head list
hPutStrLn handler line
writeLines tail list -- Should be writeLines handler $ tail list instead.
接下来是fileToList
fileToList :: FilePath -> [String] --Has to be IO [String]
fileToList filename = do
handler <- openFile filename ReadMode
list <- (readLines handler [])
hClose handler
list -- Have to use return list
哦,你似乎把线倒置了两次,所以实际上你最终得到了一个非常大的复制例程,在那里删除了反向,你得到了正确的结果。
最后的代码
import System.IO
readLines :: Handle -> [String] -> IO [String]
readLines handler list = do
eof <- hIsEOF handler
if eof
then return list
else do
line <- hGetLine handler
readLines handler (line:list)
writeLines :: Handle -> [String] -> IO ()
writeLines handler list = if length list == 0 then return ()
else do
let line = head list
hPutStrLn handler line
writeLines handler $ tail list
fileToList :: FilePath -> IO [String]
fileToList filename = do
handler <- openFile filename ReadMode
list <- (readLines handler [])
hClose handler
return list
invLines :: FilePath -> FilePath -> IO ()
invLines input output = do
handler <- openFile output WriteMode
inputLines <- fileToList input
writeLines handler inputLines
hClose handler
main = invLines "in.txt" "out.txt"
并使用更多的库重写:
invLines input output = do
inputLines <- readFile input
writeFile output . unlines . reverse . lines $ inputLines
invLines2 input output =
readFile input >>= writeFile output . unlines . reverse . lines
要学习的重要课程您不能从 IOdo
块内部返回正常功能。你必须返回一个 IO 东西