Before we dive into what we can do with Monad , let’s start by writing out our instance. You might recall that the Monad type class requires that we implement two functions: return and (>>=) . When you already have an Applicative instance, like we do, it’s usually to define return in terms of pure . So, we’ll start by defining our new class:

​  ​ instance ​ ​ Monad ​ ​ FilePackParser ​ ​ where ​
​  return = pure

Next we need to define (>>=) . As you may recall, the general type of (>>=) is:

​  (>>=) :: m a -> (a -> m b) -> m b

Or, specialized to FilePackParser :

​  (>>=) :: ​ FilePackParser ​ a -> (a -> ​ FilePackParser ​ b) -> ​ FilePackParser ​ b

We’ll start out defining a new FilePackParser and binding its input so that we can use it inside of the parser:

​  valParser >>= mkParser = ​ FilePackParser ​ $ ​ \ ​input -> ​ do ​
​  {:language=​ "haskell" ​}

(>>=) takes a parse action and a function from a value to a new parse action. We need to start by running the first parse action that we’re given so that we can get a plain value that we can pass into our function. We can do that with runParser just like we did when we defined (<*>) :

​  (val, rest) <- runParser valParser input

Finally, we’ll call our function, mkParser , with the value we just parsed. We’ll run that parser with the remainder of the input that we have left from getting the value. The result of running this second parser will be returned directly, since that’s the result of our new parser.

​  runParser (mkParser val) rest

Overall, the whole type class definition is just a few lines long:

​  ​ instance ​ ​ Monad ​ ​ FilePackParser ​ ​ where ​
​  return = pure
​  valParser >>= mkParser = ​ FilePackParser ​ $ ​ \ ​input -> ​ do ​
​  (val, rest) <- runParser valParser input
​  runParser (mkParser val) rest

So, what does this Monad instance buy us? As you’d expect, we can now use do notation instead of manually using (<$>) and (>>=) to write parsers. This improves the ergonomics of writing parsers, but it doesn’t directly give us a lot of new things we can do. More importantly is that having a Monad instance means that we have the ability to join parser actions. Joining values is best described by the join function, defined in Control.Monad . Its definition is:

​  join :: ​ Monad ​ m => m (m a) -> m a
​  join m = m >>= id

In short, join lets us take two nested monadic actions, and combine them into a single action. The ability to do this is one of the important differences between Monad and Applicative . We don’t often call join directly; instead, the fact that we’re joining values is implicit in the way we use (>>=) , but the fact that we can join values, explicitly or implicitly, also means that we can compose monadic parsers in ways that we can’t compose applicative parsers.

One example of where we need to use (>>=) or join when parsing is dealing with sub-parsers. As an example, let’s imagine that we want to support images in the Netpbm format [19] in our file archive. The Netpbm file format lets us store image data as a collection of binary or ASCII characters using a few different encoding schemes. We’re going to support two of them: PBM and PGM. Don’t worry if you’ve never heard of this format though; the details don’t matter too much for our specific example.

​  ​ data ​ ​ FilePackImage ​
​  = ​ FilePackPBM ​ ​ Word32 ​ ​ Word32 ​ [​ Word32 ​]
​  | ​ FilePackPGM ​ ​ Word32 ​ ​ Word32 ​ ​ Word32 ​ [​ Word32 ​]
​  ​ deriving ​ (​ Eq ​, ​ Show ​)
​  
​  ​ instance ​ ​ Encode ​ ​ FilePackImage ​ ​ where ​
​  encode (​ FilePackPBM ​ width height values) = encode $
​  encodeWithSize @​ String ​ ​ "pbm" ​
​  <> encodeWithSize width
​  <> encodeWithSize height
​  ​ -- The Encode instance for list already includes size info ​
​  <> encode values
​  
​  encode (​ FilePackPGM ​ width height maxValue values) = encode $
​  encodeWithSize @​ String ​ ​ "pgm" ​
​  <> encodeWithSize width
​  <> encodeWithSize height
​  <> encodeWithSize maxValue
​  ​ -- The Encode instance for list already includes size info ​
​  <> encode values

In this example, we have a sum type that lets us represent the different kinds of Netpbm formats that we might want to store. We need a way to differentiate between them so that we can decode them properly, so we’re prefixing the encoded data with a string tag. Without this tag, we wouldn’t know which of the possible formats we should decode the data into.

Using tags like this to differentiate between different constructors in a sum type is a common pattern, and you’ll see it regularly when dealing with all kinds of file formats, from image formats to other file archive formats, to commonly used serialization formats like JSON and XML. With a monadic parser we can deserialize this kind of data easily:

​  ​ instance ​ ​ Decode ​ ​ FilePackImage ​ ​ where ​
​  decode = execParser $ ​ do ​
​  tag <- extractValue @​ String ​
​  ​ case ​ tag ​ of ​
​  ​ "pbm" ​ ->
​  ​ FilePackPBM ​
​  <$> extractValue
​  
​  
​  <*> extractValue
​  <*> many extractValue
​  ​ "pgm" ​ ->
​  ​ FilePackPGM ​
​  <$> extractValue
​  <*> extractValue
​  <*> extractValue
​  <*> many extractValue
​  otherTag ->
​  ​ FilePackParser ​ $ ​ \ ​​ _ ​ -> ​ Left ​ $ ​ "unknown image type tag: " ​ <> otherTag

You’ll notice in this example we’re still making use of our Applicative instance to write the parsers for each of the specific constructors that we care about, but at the top level we’re using do notation to first extract the tag and then match on its contents to decide which of our two parsers to invoke. At first it may be tempting to try to refactor this to use applicative style parsing as well. At first glance, it seems like it shouldn’t be that hard to simplify the code to consistently use the applicative parsing style, but if we look more deeply at what the code is doing, we’ll see that it would be impossible to implement this without a Monad instance.

To understand why, let’s break this function up into a couple of pieces. First, we’ll extract each of our case branches into their own functions, parsePBM and parsePGM :

​  parsePBM, parsePGM :: ​ FilePackParser ​ ​ FilePackImage ​
​  parsePBM = ​ FilePackPBM ​ <$>
​  extractValue <*> extractValue <*> many extractValue
​  parsePGM = ​ FilePackPGM ​ <$>
​  extractValue <*> extractValue <*> extractValue <*> many extractValue

Next, let’s move the logic from our case expression into a function:

​  getNetpbmParser :: ​ String ​ -> ​ FilePackParser ​ ​ FilePackImage ​
​  getNetpbmParser tag =
​  ​ case ​ tag ​ of ​
​  ​ "pbm" ​ -> parsePBM
​  ​ "pgm" ​ -> parsePGM
​  otherTag ->
​  ​ FilePackParser ​ $ ​ \ ​​ _ ​ -> ​ Left ​ $ ​ "unknown image type tag: " ​ <> otherTag

We need the tag value to pass into getNetpbmParser . This is really just going to be a call to extractValue , but let’s make it its own function for now, just to help illustrate what’s happening:

​  getNetpbmTag :: ​ FilePackParser ​ ​ String ​
​  getNetpbmTag = extractValue

Finally, we need to compose all of these pieces into our final decoding function. Let’s write a function to do that, but before we dive into the implementation we’ll think through its type.

First, we’ll need to pass in the tag, or at least a way to get the tag, so we know what to parse, so our function will have the type:

​  parseImage :: ​ FilePackParser ​ ​ String ​ -> ???

Next, let’s pass in our getNetpbmParser function. That way we can call it with the tag as soon as we’ve parsed it out of the input. That means our type will be:

​  parseImage
​  :: ​ FilePackParser ​ ​ String ​
​  -> (​ String ​ -> ​ FilePackParser ​ ​ FilePackImage ​)
​  -> ???

The goal is to get a parser for a particular image, so let’s return the parser that we get when we call getNetpbmParser directly, without any modifications. That means the final type of our composition is:

​  parseImage
​  :: ​ FilePackParser ​ ​ String ​
​  -> (​ String ​ -> ​ FilePackParser ​ ​ FilePackImage ​)
​  -> ​ FilePackParser ​ ​ FilePackImage ​

Does this look familiar? We’ve just demonstrated exactly why we need a Monad instance, because the type we need turns out to be (>>=) !

There are two lessons to take away from this example. The first is that adding a Monad instance to a parser can offer some concrete value, especially when you might need to use information from the input you are parsing to make decisions about how to parse the rest of the document. The other lesson to take away is that even when we did have access to a Monad instance and could have used do notation, we still made use of the Applicative instance for some of our parsing as well. This is a good example of a broader pattern you’ll see when parsing things in Haskell: Applicative , Alternative , and Monad instances all work together, and it’s common to fluidly switch between the features of each when parsing things.