I am a beginner to Haskell and am trying to rewrite one of my shell scripts in Haskell as a test. One of the things I am trying to accomplish is removing the last line of a file and reading its value.
I tried to use readFile
and then writeFile
, but I can't because it is lazy.
I was able to get it to work using this code:
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as TL
erase filename = do
contents <- B.readFile filename
let array = map (T.unpack . TL.decodeUtf8) (B.lines contents)
B.writeFile filename $ B.pack (intercalate "\n" (init array))
print $ last array
This turns the lines of the file into a list and then writes to the file without the last line. It is using the ByteString so it won't be lazy. However, I think that this way is very verbose and does it weirdly. Is there some function that deletes a line from a file or how can this code be improved?