Monad transformers are tricky, and I'm not sure (= don't have good intuition) which one should go on top.
2 Answers
StateT s (ExceptT e m)
This says:
- Start with
m
- Add exceptions to that
- Add state to that
Now, 'adding exceptions' means your actions can terminate in two ways: either with a normal return value, or with an exception.
'Adding state' means that an extra bit of state output gets included in the normal return values.
So in StateT s (ExceptT e m)
, you only get a result state if there is no exception.
On the other hand,
ExceptT e (StateT s m)
says:
- Start with
m
- Add state to that
- Add exceptions to that
'Adding state' means that an extra bit of state output gets included in the return values of m
.
But now, your added exceptions get added as an alternative return value inside the StateT
monad. So you always get a state output, and then you may get a normal return value or you may get an exception along with it.
-
8This might give a more immediately clear picture, so:
StateT s (ExceptT e m) a
has the "expanded" form:s -> m (Either e (s, a))
whilstExceptT e (StateT s m)
"expands" to:s -> m (s, Either e a)
. The former allows you to roll-back changes to the state when an error occurs incatchError
, while the latter commits faulty states making them harder to rollback. In some languages you actually want the latter. Recommended reading: cse.chalmers.se/edu/course/…– CentrilNov 15, 2016 at 21:55
I answer this myself, but other answers are welcome!
Consider the example:
#!/usr/bin/env stack
-- stack runghc --package mtl
{-# LANGUAGE FlexibleContexts #-}
module Main (main) where
import Control.Applicative
import Control.Monad.State
import Control.Monad.Error
import Control.Monad.Trans.Except
import Data.Functor.Identity
test1 :: (MonadState Int m, MonadError String m) => m Bool
test1 = do
put 1
throwError "foobar"
put 2
return False
test2 :: (Alternative m, MonadState Int m, MonadError String m) => m Bool
test2 = do
put 4
test1 <|> return True
runStateExceptT :: Monad m => s -> ExceptT e (StateT s m) a -> m (Either e a, s)
runStateExceptT s = flip runStateT s . runExceptT
runExceptStateT :: Monad m => s -> StateT s (ExceptT e m) a -> m (Either e (a, s))
runExceptStateT s = runExceptT . flip runStateT s
main :: IO ()
main = do
print $ runIdentity . runStateExceptT 3 $ test1
print $ runIdentity . runExceptStateT 3 $ test1
print $ runIdentity . runStateExceptT 3 $ test2
print $ runIdentity . runExceptStateT 3 $ test2
It will print:
(Left "foobar",1)
Left "foobar"
(Right True,1)
Right (True,4)
With ExceptT
outside, you'll still get the state which was at the moment of "throwing an error". This is probably what you want.
Remember that this combination resembles imperative programming a lot. One should think about exception safety practicies, i.e. must be careful about when to throwError
!
?unmtl
in the #haskell channel.