ResourceT is a monad transformer that creates a region of code where you can safely allocate and release resources. Unlike the standard bracket pattern, which is designed for nested, statically known resource lifecycles, ResourceT allows for interleaved allocation and deallocation. This is particularly useful when the number or order of resources depends on runtime data (e.g., reading a stream and opening a new file for every chunk of data).
To use ResourceT, you typically use runResourceT to execute a block of code and allocate to register a resource with a cleanup action. You can also manually trigger the release of a resource using the releaseKey returned by allocate.
import Control.Monad.Trans.Resource
import Control.Monad.IO.Class
main :: IO ()
main = runResourceT $ do
-- allocate returns a (ReleaseKey, resource)
(releaseKey, resource) <- allocate
(putStrLn "Allocating resource" >> return 42)
(\i -> putStrLn $ "Freeing resource: " ++ show i)
-- Use the resource
liftIO $ print resource
-- Manually release the resource early if needed
release releaseKey