Error handling is just one example of how we can use monad transformers to add capabilities to other our computations. Let’s look at another example by revisiting the State monad that we defined earlier in this chapter. We defined State as a function from an old state to a value and some new state:
| | newtype State s a = State {runState :: s -> (a, s)} |
The State monad was useful because it gave us a way to write pure functions that needed access to mutable state. It’s not hard to imagine that we might have other computations that would benefit from the ability to deal with mutable state. We can do that by modeling a state transformer named StateT as a function from an input state to some monadic value that computes a value and a new state. Since we’ve seen a few examples already, let’s take a look at the full definition of StateT :
| | {-# LANGUAGE TupleSections #-} |
| | module StateT where |
| | |
| | newtype StateT s m a = StateT { runStateT :: s -> m (a, s) } |
| | |
| | evalStateT :: Monad m => StateT s m a -> s -> m a |
| | evalStateT stateAction initialState = |
| | fst <$> runStateT stateAction initialState |
| | |
| | execStateT :: Monad m => StateT s m a -> s -> m s |
| | execStateT stateAction initialState = |
| | snd <$> runStateT stateAction initialState |
| | |
| | instance Functor m => Functor ( StateT s m) where |
| | fmap f s = |
| | StateT $ fmap (first f) . runStateT s |
| | where first g (a,b) = (g a, b) |
| | |
| | instance Monad m => Applicative ( StateT s m) where |
| | pure a = StateT $ \ s -> pure (a, s) |
| | f <*> a = StateT $ \ s -> do |
| | (g,s') <- runStateT f s |
| | (b,s'') <- runStateT a s' |
| | pure (g b, s'') |
| | instance Monad m => Monad ( StateT s m) where |
| | return = pure |
| | a >>= f = StateT $ \ s -> do |
| | (b, s') <- runStateT a s |
| | runStateT (f b) s' |
| | |
| | put :: Monad m => s -> StateT s m () |
| | put state = StateT $ \ _ -> pure ((), state) |
| | |
| | get :: Monad m => StateT s m s |
| | get = StateT $ \ state -> pure (state, state) |
Once again, we can see that moving from State to StateT requires only a few minor changes to our existing code. The general shape of our Functor , Applicative , and Monad instances remain the same, but they now run inside of an m action. We still have the same basic operations, get and put , and their definitions are once again quite similar to the original definitions.
Monad Transformers and the Identity Monad
One way to look at StateT is that it’s a more flexible version of State because it allows us to add mutable state to any sort of computation. A more pessimistic view of the situation is to say that, like all monad transformers, StateT requires that we have some other computation to host the new capabilities we’re adding. This limitation is a bit of a problem, since we’ve already seen that there are some situations, like building parsers, where we might want to use State without any other underlying computation.
One way to handle this would be to define two separate modules. We could define one module for the original State , and another module for StateT that we can use if we have some other computation we’re already working with. This approach would work in theory, but it has a couple of drawbacks. First, we’d be writing a lot of duplicate code, and that invites bugs. Second, we can easily imagine a user of our library starting out using State and then realizing that they have some other effects that they need to manage, and needing to refactor their application to use StateT . Having two separate modules would introduce a much larger refactoring burden on our users in this case, since they’d need to update their code in many more places.
Thankfully, we have another option: the Identity monad. Identity is defined for us in the Data.Functor.Identity module in base , but let’s look at an example implementation so that we can understand what it does:
| | module Identity where |
| | |
| | newtype Identity a = Identity { runIdentity :: a } |
| | deriving ( Eq , Show ) |
| | |
| | instance Functor Identity where |
| | fmap f a = Identity $ f (runIdentity a) |
| | |
| | instance Applicative Identity where |
| | pure = Identity |
| | f <*> a = Identity $ runIdentity f $ runIdentity a |
| | |
| | instance Monad Identity where |
| | return = pure |
| | a >>= f = f (runIdentity a) |
As you can see, Identity doesn’t actually do much of anything by itself. All of the instances that we’ve defined are essentially just normal function application over regular values. At first Identity may seem useless, but it turns out to be quite useful when combined with monad transformers, because using Identity as the underlying monad lets us get access to the features that are added by a monad transformer without needing to have some other computation that might have side effects we don’t want or need. This is hinted at by the name identity .
Now we can take advantage of Identity to avoid duplication by defining our original State monad in terms of StateT :
| | type State s = StateT s Identity |
| | |
| | evalState :: State s a -> s -> a |
| | evalState stateAction initialState = |
| | runIdentity $ evalStateT stateAction initialState |
| | |
| | execState :: State s a -> s -> s |
| | execState stateAction initialState = |
| | runIdentity $ execStateT stateAction initialState |
Since State is just a type alias for StateT , all of our existing functions like get and put work exactly as we expect. We also have the flexibility to write our own new stateful functions that can be used with any underlying monad that our users might need. Let’s look at a small example to help illustrate the idea. We’ll start by creating a trivial stateful function. In the example, we’ll define a function called duplicate that reads the mutable state and returns it twice, in a tuple. You can pick some other simple function as you work through the example if you like.
| | duplicate :: Monad m => StateT a m (a,a) |
| | duplicate = do |
| | val <- get |
| | pure (val,val) |
In this example, we’re not depending on any particular inner monad; that means we are free to pick whichever type of computation we happen to need. For example, let’s write a function that uses duplicate as though it were a plain State action. We’ll start with a more verbose implementation that makes it clear what particular type we’re using for duplicate :
| | pureDuplicate :: Int -> ( Int , Int ) |
| | pureDuplicate val = evalState getDuplicate val |
| | where |
| | getDuplicate :: State Int ( Int , Int ) |
| | getDuplicate = duplicate |
The definition of getDuplicate here isn’t necessary except to help make the types more clear. We can also write this more simply as:
| | pureDuplicate :: Int -> ( Int , Int ) |
| | pureDuplicate = evalState duplicate |
We can also pick some other monad, like IO . Let’s start with a more verbose version again:
| | printDuplicate :: Int -> IO () |
| | printDuplicate val = evalStateT getDuplicate val >>= print |
| | where |
| | getDuplicate :: StateT Int IO ( Int , Int ) |
| | getDuplicate = duplicate |
In this example, we’re using IO as our inner computation. That means the result of evalStateT will be an IO action that we can easily pass to print .