O'Reilly logo

Developing Web Applications with Haskell and Yesod by Michael Snoyman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Resource Monad Transformer

The Resource transformer (ResourceT) plays a vital role in proper resource management in the conduit project. It is included within the conduit package itself. We’ll explain ResourceT as its own entity. While some of the design decisions clearly are biased toward conduits, ResourceT should remain a usable tool in its own right.

Goals

What’s wrong with the following code?

import System.IO

main = do
    output <- openFile "output.txt" WriteMode
    input  <- openFile "input.txt"  ReadMode
    hGetContents input >>= hPutStr output
    hClose input
    hClose output

If the file input.txt does not exist, then an exception will be thrown when trying to open it. As a result, hClose output will never be called, and we’ll have leaked a scarce resource (a file descriptor). In our tiny program, this isn’t a big deal, but clearly we can’t afford such waste in a long running, highly active server process.

Fortunately, solving the problem is easy:

import System.IO

main =
    withFile "output.txt" WriteMode $ \output ->
    withFile "input.txt" ReadMode $ \input ->
    hGetContents input >>= hPutStr output

withFile makes sure that the Handle is always closed, even in the presence of exceptions. It also handles asynchronous exceptions. Overall, it’s a great approach to use…when you can use it. While often withFile is easy to use, sometimes it can require restructuring our programs. And this restructuring can range from mildly tedious to wildly inefficient.

Let’s take enumerators for example. If you look ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required