Resource management with bracket
So far, we have been explicitly opening and closing files. This is what we call explicit resource management:
main = do h <- (openFile "jabberwocky.txt" ReadMode) useResource h hClose h where useResource h' = (stream h') >>= mapM_ putStrLn stream h' = hGetContents h' >>= return . lines
Let's look at some higher level abstractions to capture this pattern: open resource, use it, in some way clean up resource. The crudest solution is to just ignore the problem and rely on the garbage collector for the cleanup:
main = do
contents <- readFile "jabberwocky.txt"
mapM_ putStrLn (lines contents)
The readFile
function encapsulates the file handle, which is then garbage collected when the contents
function is garbage collected or when it has been entirely consumed. This is very poor resource management!
It would be more idiomatic to use the wrapper function withFile
:
main...