Now that we’ve seen how to combine different effects using monad transformers, and defined transformers for both ExceptT and StateT , we find ourselves with a bit of a problem: how should we nest them? Consider the parser example we’ve been using throughout this chapter. Should we define one by nesting a StateT inside of an ExceptT , or vice versa? Let’s take a look at the two options to see what impact the choice we have might make.

Nesting State Inside of Except

Let’s start by continuing the pattern we’ve used so far in this chapter, using State as the inner monad and adding ExceptT to give it the ability to handle errors. First, we’ll create a new module, add some imports, and define a type alias for our parser:

​  ​ {-# LANGUAGE OverloadedStrings #-} ​
​  
​  ​ module ​ ​ ExceptState ​ ​ where ​
​  
​  ​ import ​ ​ Control.Applicative ​
​  ​ import ​ ​ Control.Monad ​ (​ when ​, ​ void ​)
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ Text
​  ​ import ​ ​ ExceptT ​
​  ​ import ​ ​ StateT ​
​  
​  ​ type ​ ​ ParseError ​ = ​ Text ​
​  ​ type ​ ​ ParseState ​ = ​ Text ​
​  
​  ​ type ​ ​ Parser ​ = ​ ExceptT ​ ​ ParseError ​ (​ State ​ ​ ParseState ​)
​  
​  runParser :: ​ Text ​ -> ​ Parser ​ a -> ​ Either ​ ​ ParseError ​ a
​  runParser input parser =
​  evalState (runExceptT parser) input

So far, everything is looking very much like the other parsers that we’ve defined in this chapter. Let’s go ahead and add two short parsing functions to build our example on. We’ll start with a parser that will get the next character from the parse state, and return an error if we’re at the end of our input:

​  parseChar :: ​ Parser ​ ​ Char ​
​  parseChar = ​ do ​
​  parseState <- succeed get
​  ​ case ​ ​ Text ​.uncons parseState ​ of ​
​  ​ Nothing ​ -> throwError ​ "end of input" ​
​  ​ Just ​ (c, rest) -> ​ do ​
​  succeed $ put rest
​  pure c

In this example, remember that we need to use succeed when we want to get or put a value to lift the State action into ExceptT . Next, let’s add a parser that lets us say that we expect the next character of the parse state to be some particular character. If it is, then we’ll discard it, otherwise we’ll raise an error:

​  char :: ​ Char ​ -> ​ Parser ​ ()
​  char expectedChar = ​ do ​
​  actualChar <- parseChar
​  when (expectedChar /= actualChar) $
​  throwError ​ "Invalid character" ​

So far, so good. We can load this parser up into ghci and see it working:

​  ​ λ ​ runParser ​ "123" ​ parseChar
​  ​ Right ​ ​ '1' ​
​  ​ λ ​ runParser ​ "123" ​ (parseChar >> parseChar)
​  ​ Right ​ ​ '2' ​
​  ​ λ ​ runParser ​ "abc" ​ (char ​ 'a' ​ >> parseChar)
​  ​ Right ​ ​ 'b' ​
​  ​ λ ​ runParser ​ "abc" ​ (char ​ '1' ​ >> parseChar)
​  ​ Left ​ ​ "Invalid character" ​

Next, let’s say that we want to add a parser that will remove any leading spaces from our input. One way we can do that is to repeatedly match a single space and discard it, continuing to do so until trying to match a space fails. You may recall that we encountered a similar problem when building the FilePack parser . In that example, we defined an instance of the Alternative type class to help us parse a list of values. Let’s see if we can do the same thing now.

We’ll start by returning to our ExceptT module. We’ll add an import for Control.Applicative , then we can start defining our instance. Let’s look at the definition first and then walk through it:

​  ​ instance ​ (​ Monoid ​ e, ​ Monad ​ m) => ​ Alternative ​ (​ ExceptT ​ e m) ​ where ​
​  empty = ​ ExceptT ​ (pure $ ​ Left ​ mempty)
​  a <|> b = ​ ExceptT ​ $ ​ do ​
​  a' <- runExceptT a
​  ​ case ​ a' ​ of ​
​  ​ Right ​ val -> pure (​ Right ​ val)
​  ​ Left ​ err -> ​ do ​
​  b' <- runExceptT b
​  ​ case ​ b' ​ of ​
​  ​ Right ​ val -> pure (​ Right ​ val)
​  ​ Left ​ err' -> pure (​ Left ​ $ err <> err')

Like all of the instances we’ve defined for ExceptT , we’re adding a constraint that m must be a Monad . This lets us use do notation, and it gives us a way to access values from the inner computation. We’re also adding a new constraint, requiring that the error type be a Monoid . We’re adding this constraint so that we can use mempty to create a new error when empty occurs. Since the error could be any type, we need some way to create a default value, and mempty is a reasonable choice. As an additional benefit, if both of the alternatives fail in (<|>) , we can combine the errors and show the user both of them.

The implementation of empty is straightforward. We fail and set the error to some empty default error value. The definition of (<|>) is longer, but also fairly mechanical. First we try to run the left-hand computation. If it succeeds, we use that value. If not, we try to run the right-hand computation, returning that value if it succeeds, and otherwise returning both errors.

We can use our new instance directly in ghci to try out some alternative parsing. For example, if we try some simple examples throwing exceptions, we can see everything acting like we’d hope:

​  λ runParser "hello" $ throwError "bad" <|> pure "good"
​  Right "good"
​  λ runParser "hello" $ pure "good" <|> throwError "bad"
​  Right "good"
​  λ runParser "hello" $ pure "good" <|> pure "better"
​  Right "good"
​  λ runParser "hello" $ throwError "bad" <|> throwError "worse"
​  Left "badworse"

What if we try to use this with our parsing code? Let’s try an experiment: if the first character of our input string is the letter a , we’ll discard it and return the second character. Otherwise, we’ll return the first character:

​  ​ λ ​ runParser ​ "abc" ​ $ (char ​ 'a' ​ >> parseChar) <|> parseChar
​  ​ Right ​ ​ 'b' ​

So far, so good. We discarded the first character and returned the second. Let’s try again with different input so we can exercise the other half of our expression:

​  ​ λ ​ runParser ​ "123" ​ $ (char ​ 'a' ​ >> parseChar) <|> parseChar
​  ​ Right ​ ​ '2' ​

That doesn’t look right at all…what’s going on? We can get a hint as to the problem if we look back at the instance we defined for FilePackParser :

​  ​ instance ​ ​ Alternative ​ ​ FilePackParser ​ ​ where ​
​  empty = fail ​ "empty parser" ​
​  parserA <|> parserB = ​ FilePackParser ​ $ ​ \ ​s ->
​  ​ case ​ runParser parserA s ​ of ​
​  ​ Right ​ val -> ​ Right ​ val
​  ​ Left ​ ​ _ ​ -> runParser parserB s

In our FilePackParser instance, the very first line of our definition of (<|>) is:

​  parserA <|> parserB = ​ FilePackParser ​ $ ​ \ ​s ->

That means the rest of the body of our definition is happening inside of the function from the previous parse state to the next one. In other words, the exception handling for FilePackParser is embedded inside of the mutable state. In our new transformer-based parser we’re doing things the other way around, embedding the mutable state inside of the exception handling.

The result of this decision is that each of our two alternative parsers are going to run inside of a single computation and share a single mutable state. When we run the first parser, even though it fails, the side effects persist as we move on to the second parser. In our ghci examples, even though char ’a’ fails to match a character, it still consumes a value from the parse state.

The choice of how we define our monad transformer stack can have other implications too. Another example that we can easily demonstrate with Alternative is the order in which we nest our transformers is impacted by the laziness of the computations we’re nesting. The many function, for example, won’t terminate with our current Parser definition. You can see this yourself in ghci ; remember you can press ctrl-c to stop a function that isn’t terminating:

​  ​ λ ​ runParser ​ "abc" ​ (many parseChar)
​  ​ Interrupted ​.

Why does this fail to run? Because our definition of StateT is strict, we end up accidentally trying to evaluate an infinite list of parser actions before we look for the ones that succeeded.

Nesting Except Inside of StateT

Nesting State inside of ExceptT has clearly not worked out as well as we might have hoped. Thankfully, we’ve got an easily available alternative. We can nest Except inside of StateT instead. To start, let’s return to our example and add a new type alias, Except :

​  ​ import ​ ​ Identity ​
​  
​  ​ type ​ ​ Except ​ e = ​ ExceptT ​ e ​ Identity ​
​  
​  runExcept :: ​ Except ​ e a -> ​ Either ​ e a
​  runExcept = runIdentity . runExceptT

As you can see, Except is analogous to State ; it uses Identity as an inner monad. In practice, Except is more or less identical to Either , but the new type alias lets us keep consistency with some of our earlier examples.

Next, we’ll head over to the StateT module. Since StateT will be our outer monad transformer, we’ll need to add an Alternative instance for it:

​  ​ import ​ ​ Control.Applicative ​
​  
​  ​ instance ​ (​ Monad ​ m, ​ Alternative ​ m) => ​ Alternative ​ (​ StateT ​ s m) ​ where ​
​  empty = ​ StateT ​ $ const empty
​  a <|> b = ​ StateT ​ $ ​ \ ​s ->
​  runStateT a s <|> runStateT b s

Unlike the Alternative instance we defined for ExceptT , this instance requires that our inner monad also have an Alternative instance. Thankfully, we defined one for ExceptT in the previous example, so we don’t have any more work to do.

While we’re editing the StateT module, there’s another function that we’ll need to add. When we were using ExceptT as our outer monad, we had to define the succeed function as a way to lift a State action like get or put into the transformer. Now that we’re embedding Except inside of StateT we’ll have a similar problem. We can use get and put directly, but we need a way to lift an Except computation, like throwError , into the StateT transformer. Let’s call the function liftStateT :

​  liftStateT :: ​ Monad ​ m => m a -> ​ StateT ​ s m a
​  liftStateT a = ​ StateT ​ $ ​ \ ​s -> (, s) <$> a

Now that we have updated our transformer modules, let’s create a new module for our new parser. Like before, we’ll start with a type alias for our parser, and define functions to extract a single character, or to expect a particular character:

​  ​ {-# LANGUAGE OverloadedStrings #-} ​
​  
​  ​ module ​ ​ StateExcept ​ ​ where ​
​  
​  ​ import ​ ​ Control.Applicative ​
​  ​ import ​ ​ Control.Monad ​ (​ when ​, ​ void ​)
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ Text
​  ​ import ​ ​ ExceptT ​
​  ​ import ​ ​ StateT ​
​  
​  ​ type ​ ​ ParseError ​ = ​ Text ​
​  ​ type ​ ​ ParseState ​ = ​ Text ​
​  
​  ​ type ​ ​ Parser ​ = ​ StateT ​ ​ ParseState ​ (​ Except ​ ​ ParseError ​)
​  
​  runParser :: ​ Text ​ -> ​ Parser ​ a -> ​ Either ​ ​ ParseError ​ a
​  runParser input parser =
​  runExcept $ evalStateT parser input
​  
​  parseChar :: ​ Parser ​ ​ Char ​
​  parseChar = ​ do ​
​  parseState <- get
​  ​ case ​ ​ Text ​.uncons parseState ​ of ​
​  ​ Nothing ​ -> liftStateT $ throwError ​ "end of input" ​
​  ​ Just ​ (c, rest) -> ​ do ​
​  put rest
​  pure c
​  
​  char :: ​ Char ​ -> ​ Parser ​ ()
​  char expectedChar = ​ do ​
​  actualChar <- parseChar
​  when (expectedChar /= actualChar) $
​  liftStateT $ throwError ​ "Invalid character" ​

Let’s give our newly refactored parser a try in ghci and see how it handles our parsing requirements. First, we’ll re-try our alternative examples:

​  ​ λ ​ runParser ​ "123" ​ $ (char ​ '1' ​ >> parseChar) <|> parseChar
​  ​ Right ​ ​ '2' ​
​  ​ λ ​ runParser ​ "123" ​ $ (char ​ 'a' ​ >> parseChar) <|> parseChar
​  ​ Right ​ ​ '1' ​

Success! When the first parser succeeds in matching the character 1 , we return the next character. More importantly, when it fails we no longer keep the side effects from the failed alternative. Instead, we compute the right-hand side using the pristine initial state.

Let’s see how our new parser handles many :

​  ​ λ ​ runParser ​ "123" ​ (many parseChar)
​  ​ Right ​ ​ "123" ​

Once again, refactoring our parser to embed exception handling inside of our state actions instead of the other way around has fixed our problem.

As you can see from these examples, when you are working with monad transformers it’s important to be considerate about the order of composition. The particular requirements of your application, and the implementation of the transformers, will be important as you think about how to structure your application.