Monad transformers
Why a transformer
A real program usually needs two effects at once: a counter and printing, or a lookup that may fail and a log. One monad cannot be another, so the libraries provide transformers: StateT s m is a state monad whose base monad is m, and MaybeT m is a Maybe on top of m. The type tells the stack:
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
StateT Int IO is a counter that can print: runStateT gives an IO (a, Int). MaybeT IO is a computation that may fail after doing IO: runMaybeT gives an IO (Maybe a). The inner monad is always the one the program finally has to run in.
StateT over IO
liftIO brings an IO action into the stack. The state operations get and modify' work as before, because the instances of mtl lift them:
module Main (main) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State (StateT, get, modify', runStateT)
type Counter = StateT Int IO
tick :: Counter ()
tick = do
modify' (+ 1)
n <- get
liftIO (putStrLn ("tick " ++ show n))
main :: IO ()
main = do
(_, final) <- runStateT (mapM_ (const tick) [1, 2, 3 :: Int]) 0
print final
ghc -Wall -O1 -o countert countert.hs
./countert
tick 1
tick 2
tick 3
3
The program has both effects and neither is simulated: the printing is real IO, and the counter is the state of the transformer. The last line is the final state that runStateT returned, and it is 3 because three ticks ran. Without the transformer the same program would pass the counter through every function or store it in an IORef.
MaybeT and a lookup that fails
A lookup that logs its attempt and may fail is a MaybeT IO. lift is the general form of liftIO and works for any inner monad:
module Main (main) where
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT)
lookupUser :: String -> MaybeT IO String
lookupUser name = do
lift (putStrLn ("looking up " ++ name))
case name of
"ada" -> pure "admin"
"bob" -> pure "user"
_ -> MaybeT (pure Nothing)
main :: IO ()
main = do
print =<< runMaybeT (lookupUser "ada")
print =<< runMaybeT (lookupUser "zoe")
ghc -Wall -O1 -o lookup lookup.hs
./lookup
looking up ada
Just "admin"
looking up zoe
Nothing
The failure is a value of the inner Maybe, so the program did not throw and did not need a pattern match at the call site: runMaybeT gave an IO (Maybe String) and the two results are printed with their reason. The order of the output is the order of the actions: the log line of a failed lookup still appears, because the IO happened before the failure.
A stack of two pure monads
The base monad does not have to be IO. StateT Int (Either String) is a counter that can fail, and lift (Left ...) is the failure:
module Main (main) where
import Control.Monad.State (StateT, get, modify', runStateT)
import Control.Monad.Trans.Class (lift)
type Checked = StateT Int (Either String)
add :: Int -> Checked ()
add n = do
total <- get
if total + n > 100
then lift (Left ("over the limit: " ++ show (total + n)))
else modify' (+ n)
main :: IO ()
main = do
print (runStateT (mapM_ add [10, 20, 30]) 0)
print (runStateT (mapM_ add [10, 20, 80]) 0)
ghc -Wall -O1 -o checked checked.hs
./checked
Right ((),60)
Left "over the limit: 110"
The successful run gives Right with the unit value and the final counter. The failing run gives the error and no state, because Either is the outer type once the computation is run: the state is inside the failure and is lost with it. That is a design decision of this stack: once the computation has failed, the state it had reached is not part of the answer.
lift and the order of the layers
Two functions do the work of moving between layers:
- lift brings an action of the inner monad into the transformed stack, for any inner monad.
- liftIO is lift specialised to IO and works at any depth, which is why the code above does not count the layers.
The order of the layers shows in the runner type: runStateT of a StateT Int IO gives IO (a, Int), while runMaybeT of a MaybeT (State Int) would give State Int (Maybe a). Swap the layers and the type changes, so the stack is not a set but an order: decide which effect is outermost from the type of the final runner.
Exercises
- Add a log to the counter with StateT Int (Writer [String]) and run it.
- Write safeDiv :: Int -> Int -> MaybeT IO Int that prints its arguments and fails on a zero divisor.
- Explain the type of runStateT for StateT Int IO and for StateT Int (Either String).
- Replace liftIO with lift in the counter and say why it does not type check.
- Run the checked counter with limits of 60 and 100 and compare the outputs.
- Explain why MaybeT keeps the IO that ran before the failure.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
StateT s m aat run time?Answer
A function from the state to an action in m that returns a value and a state
runStateT :: s -> m (a, s), so the state is threaded through the inner monad. -
What does
liftIOdo?Answer
Brings an IO action into the transformed stack
liftIO is the IO specialisation of lift and works at any depth of the stack.
-
What does
runMaybeT (pure 3 :: MaybeT IO Int)give?Answer
IO (Just 3)The runner gives an action of the inner monad that produces a Maybe.
-
What does this program print?
module Main (main) where import Control.Monad.State (runStateT) main :: IO () main = print =<< runStateT (pure (7 :: Int)) (1 :: Int)Answer
(7,1)
The computation returns 7 and leaves the state at 1.
-
Which layer is outermost in
StateT Int (Either String)?Answer
Either, because the runner gives
Either String (a, Int)The base monad wraps the pair, so the failure is outside the state.
-
What does this program print?
module Main (main) where import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT) main :: IO () main = print =<< runMaybeT (MaybeT (pure Nothing) :: MaybeT IO Int)Answer
Nothing
The inner action produces Nothing, and the runner gives it back as an IO result.
-
Why does the counter still use
getandmodify'insideStateT?Answer
The mtl instances lift the state operations through the transformer
The MonadState instance of StateT makes the operations work on the state inside the stack.
-
What is
liftused for?Answer
To bring an action from the inner monad into the transformer
lift is the general operation that embeds the base monad; liftIO is its IO case.
-
What does a failed
MaybeT IOaction keep?Answer
The IO that ran before the failure, and Nothing as the result
The failure is a value of the inner monad, so the effects before it already happened.
-
Which runner belongs to
StateT?Answer
runStateTEach transformer has its own runner: runStateT, runMaybeT, runReaderT and so on.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev