An example Haskell program to copy data from one handle to another might
look like this:
main =
withFile "inFile.txt" ReadMode $ \inHandle ->
withFile "outFile.txt" WriteMode $ \outHandle ->
copy inHandle outHandle
-- A hypothetical function that copies data from one handle to another
copy :: Handle -> Handle -> IO ()
System.IO.withFile is one of many functions that acquire some resource in
an exception-safe way. These functions take a callback function as an
argument and they invoke the callback on the resource when it becomes
available, guaranteeing that the resource is properly disposed if the
callback throws an exception.
These functions usually have a type that ends with the following pattern:
Callback
-- -----------
withXXX :: ... -> (a -> IO r) -> IO r
Here are some examples of this pattern from the base libraries:
withArray :: Storable a => [a] -> (Ptr a -> IO r) -> IO r
withBuffer :: Buffer e -> (Ptr e -> IO r) -> IO r
withCAString :: String -> (CString -> IO r) -> IO r
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO r) -> IO r
withMVar :: Mvar a -> (a -> IO r) -> IO r
withPool :: (Pool -> IO r) -> IO r
Acquiring multiple resources in this way requires nesting callbacks.
However, you can wrap anything of the form ((a -> IO r) -> IO r) in the
Managed monad, which translates binds to callbacks for you:
This lets you combine managed resources transparently. You can also lift
operations from some numeric type classes this way, too, such as the Num
type class.
NOTE: Managed may leak space if used in an infinite loop like this
example:
If you need to acquire a resource for a long-lived loop, you can instead
acquire the resource first and run the loop in IO, using either of the
following two equivalent idioms:
with resource (\r -> forever (useThe r))
do r <- resource
liftIO (forever (useThe r))
This is a potentially unsafe function since it allows a resource to escape
its scope. For example, you might use Managed to safely acquire a
file handle, like this:
import qualified System.IO as IO
example :: Managed Handle
example = managed (IO.withFile "foo.txt" IO.ReadMode)
... and if you never used the with function then you would never run the
risk of accessing the Handle after the file was closed. However, if you
use with then you can incorrectly access the handle after the handle is
closed, like this:
bad :: IO ()
bad = do
handle <- with example return
IO.hPutStrLn handle "bar" -- This will fail because the handle is closed
... so only use with if you know what you are doing and you're returning
a value that is not a resource being managed.
Monads in which IO computations may be embedded.
Any monad built by applying a sequence of monad transformers to the
IO monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO
is a transformer of monads:
Lift a computation from the IO monad.
This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations
(i.e. IO is the base monad for the stack).
Example
import Control.Monad.Trans.State -- from the "transformers" library
printState :: Show s => StateT s IO ()
printState = do
state <- get
liftIO $ print state
Had we omitted liftIO, we would have ended up with this error:
• Couldn't match type ‘IO’ with ‘StateT s IO’
Expected type: StateT s IO ()
Actual type: IO ()
The important part here is the mismatch between StateT s IO () and IO ().
Luckily, we know of a function that takes an IO a and returns an (m a): liftIO,
enabling us to run the program and see the expected results: