I try to learn Haskell before my exam session and it’s still magic for me. Today I tried to write a program, which reads a file, and writes it’s lines in reversed order to another file. Result? Lots of errors. Here is my code:
import IO
readLines :: Handle -> [String] -> [String]
readLines handler list = do
eof <- hIsEOF handler
if eof then list
else do
line <- hGetLine handler
readLines handler (list ++ [line])
writeLines :: Handle -> [String] -> [String]
writeLines handler list = if length list == 0 then list
else do
line <- head list
hPutStrLn handler line
writeLines tail list
fileToList :: FilePath -> [String]
fileToList filename = do
handler <- openFile filename ReadMode
list <- (readLines handler [])
hClose handler
list
invLines :: FilePath -> FilePath -> IO ()
invLines input output = do
handler <- openFile output WriteMode
inverted <- reverse (fileToList input)
writeLines handler inverted
hClose handler
main = invLines "in.txt" "out.txt"
I will be grateful if you can explain me my mistakes.
Ok first of,
next let’s look at readLines (PS readFile would work nicely here)
Next onto
writeLines(PSwriteFilewould also help)Next is
fileToListOh and you seem to invert the lines twice, so you actually end up with a very large copying routine, removing the reverse in there and you get the correct result.
The Code at The End
And rewritten using more of the library:
Big lesson to learn You can’t return normal functions from inside an IO
doblock. You must return an IO something