Haskell Monad Transformers
Each monad gives you one capability: Maybe can fail, State carries state, IO talks to the world. Real code often needs several at once: "a computation that keeps a counter, can fail with an error message, and prints log lines". Monad transformers stack capabilities on top of each other. The transformers and mtl packages, both bundled with GHC, provide them.
The idea
A transformer is a monad with a hole for another monad underneath. StateT s m a is "State, on top of monad m":
| Transformer | Adds | Run with |
|---|---|---|
StateT s m |
a state of type s |
runStateT, evalStateT, execStateT |
ReaderT r m |
a read-only environment r (configuration) |
runReaderT |
WriterT w m |
an accumulated log w (a monoid) |
runWriterT |
ExceptT e m |
failure with an error e |
runExceptT |
MaybeT m |
failure without a reason | runMaybeT |
The plain monads are transformers over Identity, a do-nothing monad: State s = StateT s Identity.
StateT over IO
The most common stack: state plus real I/O. Use lift (or liftIO) to run an IO action inside the transformer:
import Control.Monad.State
-- A bank account: the state is the balance
deposit :: Int -> StateT Int IO ()
deposit amount = do
modify (+ amount)
balance <- get
lift (putStrLn ("deposited " ++ show amount ++ ", balance " ++ show balance))
withdraw :: Int -> StateT Int IO Bool
withdraw amount = do
balance <- get
if amount > balance
then do
liftIO (putStrLn ("refused: cannot withdraw " ++ show amount))
return False
else do
put (balance - amount)
liftIO (putStrLn ("withdrew " ++ show amount))
return True
main :: IO ()
main = do
(ok, final) <- runStateT (deposit 100 >> withdraw 30 >> withdraw 500) 0
print (ok, final)deposited 100, balance 100
withdrew 30
refused: cannot withdraw 500
(False,70)
runStateT takes the computation and the initial state and gives back an IO action that returns (result, finalState).
ReaderT: configuration without passing arguments
ReaderT makes a value available everywhere in a computation, like a read-only global, without passing it to every function:
import Control.Monad (when)
import Control.Monad.Reader
data Config = Config {appName :: String, verbose :: Bool, currency :: String}
logLine :: String -> ReaderT Config IO ()
logLine msg = do
v <- asks verbose
when v $ liftIO (putStrLn ("[debug] " ++ msg))
price :: Double -> ReaderT Config IO String
price amount = do
logLine ("formatting " ++ show amount)
cur <- asks currency
return (show amount ++ " " ++ cur)
app :: ReaderT Config IO ()
app = do
name <- asks appName
liftIO (putStrLn ("Welcome to " ++ name))
p <- price 9.5
liftIO (putStrLn ("Total: " ++ p))
main :: IO ()
main = do
runReaderT app (Config "TinyShop" True "EUR")
putStrLn "---"
runReaderT app (Config "TinyShop" False "USD")Welcome to TinyShop
[debug] formatting 9.5
Total: 9.5 EUR
---
Welcome to TinyShop
Total: 9.5 USD
asks field reads a part of the environment; ask reads all of it.
ExceptT: errors that stop the computation
ExceptT e m adds Either-style failure to another monad. throwError stops the computation; runExceptT returns an Either:
import Control.Monad.Except
import Control.Monad.State
data AppError = NotFound String | Insufficient Int
deriving Show
type Inventory = [(String, Int)]
type App = ExceptT AppError (State Inventory)
takeItem :: String -> Int -> App ()
takeItem item qty = do
inv <- get
case lookup item inv of
Nothing -> throwError (NotFound item)
Just have
| have < qty -> throwError (Insufficient have)
| otherwise -> put [(i, if i == item then n - qty else n) | (i, n) <- inv]
runApp :: App a -> Inventory -> (Either AppError a, Inventory)
runApp app = runState (runExceptT app)
main :: IO ()
main = do
let inv = [("bolt", 10), ("nut", 4)]
print (runApp (takeItem "bolt" 3 >> takeItem "nut" 4) inv)
print (runApp (takeItem "bolt" 3 >> takeItem "gear" 1) inv)
print (runApp (takeItem "nut" 9) inv)(Right (),[("bolt",7),("nut",0)])
(Left (NotFound "gear"),[("bolt",7),("nut",4)])
(Left (Insufficient 4),[("bolt",10),("nut",4)])
Note the second result: the state changes made before the error (3 bolts taken) are kept, because the error layer sits on top of the state layer. Stacking the layers in the other order (StateT Inventory (Either AppError)) would discard the state on failure. The order of a stack matters.
mtl style: get and throwError work anywhere
You may have noticed that get and put worked in the ExceptT … (State …) stack without any lift. That is the mtl design: classes like MonadState s m, MonadReader r m and MonadError e m let these operations find the right layer automatically. You can even write functions that work in any stack that has a capability:
import Control.Monad (when)
import Control.Monad.State
tick :: MonadState Int m => m ()
tick = modify (+ 1)
countTo :: (MonadState Int m, MonadIO m) => Int -> m ()
countTo n = do
tick
c <- get
liftIO (putStrLn ("count = " ++ show c))
when (c < n) (countTo n)
main :: IO ()
main = do
print (execState (tick >> tick >> tick) 0) -- pure State
final <- execStateT (countTo 3) 0 -- StateT over IO
print final3
count = 1
count = 2
count = 3
3
Tip: Keep stacks small. Many applications use one stack, often
ReaderT Config IO, and keep the rest of the code pure. Reach for a transformer when a capability is genuinely needed in many places.
Test yourself
What does lift do in a StateT Int IO computation?
- Runs a pure function
- Runs an action of the underlying
IOmonad inside the transformer - Reads the state
- Ends the computation
Which transformer provides a read-only configuration value?
StateTWriterTReaderTExceptT
What is State s defined as in the transformers library?
- A built-in type
StateT s IOStateT s IdentityReaderT s Maybe