Monadic parsers are a common pattern in Haskell applications. The term monadic in a monadic parser is a little bit misleading, because as you’ll see later on in this chapter, a lot of the benefit from this style of parsing comes from its Applicative instance, rather than its Monad instance. Still, creating a Parser monad allows users of our library to use the familiar do notation.
To get an idea of where we’re going and what this will look like in practice, let’s start with a short demo of what it will look like to decode the values that we encoded in testEncodeValue earlier:
| | testDecodeValue |
| | :: ByteString |
| | -> Either String |
| | ( FileData String |
| | , FileData [ Text ] |
| | , FileData ( Word32 , String ) |
| | ) |
| | testDecodeValue = decodeAndParse $ do |
| | a <- extractValue |
| | b <- extractValue |
| | c <- extractValue |
| | pure (a,b,c) |
So far we’ve been parsing things using one-off functions to parse different types of data, and each of our functions have had a slightly different type, depending on the particulars of what we were doing and what we were trying to parse. As we’re building our monadic parsing library we’ll still be building up a number of small functions, but we want those to capture the differences in the logic for the different things that we want to parse. To distill out the important differences, we should start by looking at the commonalities. One of the things that a lot of these functions had in common is that they have a very similar type. If we were to define a general parsing function, we might give it this type:
| | parseFunction :: Decode a => ByteString -> Either String (a, ByteString ) |
In other words, functions that take some input and return either an error, or a tuple of a parsed value and the remainder of the input that wasn’t consumed parsing that value. Let’s start building our monadic parser by creating a newtype wrapper around functions with that general type. We’ll omit the Decode constraint for now to keep things more general:
| | newtype FilePackParser a = FilePackParser |
| | { runParser :: ByteString -> Either String (a, ByteString ) } |
You learned much earlier in this book, when you first started creating your own types how creating a data type that held a function could let you write code that was easier to compose, and in the previous chapter, you learned how you could create an instance of Functor for a regular function. Now we’ll build on some of those ideas as we’re creating our monadic parser, starting with defining a Functor instance for FilePackParser .
If we want to eventually create a Monad instance for FilePackParser , we’ll need to start by creating a Functor instance. Remember that creating a Functor instance requires that we define a single function, fmap . For our purposes, the type of fmap will be:
| | fmap :: (a -> b) -> FilePackParser a -> FilePackParser b |
So, we want to take a function and a parser, and return a new parser that applies the function to the value that we’ve just parsed. Let’s start with a bit of a naive implementation that makes it clear what’s happening, and then we’ll refactor it into something more idiomatic.
The function we call fmap with—let’s name it changeParsedOutput —needs to work on a value we’ve actually already parsed. To get a parsed value, we need the parser we are mapping over—let’s call that parseFunction —and we need some input data we can apply to parseFunction to get output out. We know what we need, so let’s start our implementation by writing a helper function:
| | functorHelper |
| | :: (a -> b) |
| | -> ( ByteString -> Either String (a, ByteString )) |
| | -> ByteString |
| | -> Either String (b, ByteString ) |
| | functorHelper changeParsedOutput parseFunction input = do |
| | (parsedValue, remainder) <- parseFunction input |
| | pure (changeParsedOutput parsedValue, remainder) |
So, our helper function tries to parse input with parseFunction and, if we fail, we propagate the error. If we succeed though, we take the result of our parsing and apply it to changeParsedOutput to get the new result that we want, and we return that along with the unmodified remainder leftover from when we parsed our original value.
Let’s look at how we can use this to create a Functor instance:
| | instance Functor FilePackParser where |
| | fmap changeParsedOutput parser = FilePackParser $ \ input -> |
| | functorHelper changeParsedOutput (runParser parser) input |
As you can see, this definition of fmap offloads most of the work to the helper function we’ve just written. We pass along changeParsedOutput completely unmodified, along with the parse function that’s inside of parser . We also need to pass along some input so we can actually run the parser. We get that input by passing along the input that is given when we run the FilePackParser we’re returning. The first time you encounter this pattern it can be a bit confusing trying to understand where our input is actually coming from. It can seem like we’re introducing input magically. The thing to remember is since FilePackParser holds a function, at some point our user will eventually give us an input string to start with, and that will become the value of input that we use.
To cement this idea, let’s work through a short example. For the sake of simplicity we won’t really parse much of anything in this example, but we’ll start with a “parser” that tries to take the first ten characters out of an input, and counts the number of occurrences of the letter “a”.
| | parseCount :: FilePackParser Int |
| | parseCount = FilePackParser $ \ input -> |
| | let |
| | countLetters letter = |
| | BS .length . BC .filter (== letter) |
| | in |
| | if BS .length input < 10 |
| | then Left "Error: not enough input" |
| | else |
| | let (toParse, rest) = BS .splitAt 10 input |
| | in Right (countLetters 'a' toParse, rest) |
In this example, we’re using the same pattern of creating a FilePackParser by passing it a function that uses some input. We can run it with a few different inputs to see how it parses each of them:
| | λ runParser parseCount "aaaaaaaaaaaa" |
| | Right (10,"aa") |
| | λ runParser parseCount "bbbaaaaaaaaa" |
| | Right (7,"aa") |
| | λ runParser parseCount "bbbaaaaa" |
| | Left "Error: not enough input" |
If we use our Functor instance, you’ll see that we’re in a similar situation; we’re getting back a FilePackParser that still needs some input in order to do anything.
| | λ showParseCount = fmap show parseCount |
| | λ runParser showParseCount "aaaaaaaaaaaa" |
| | Right ( "10" , "aa" ) |
| | λ reverseShowParseCount = reverse <$> show <$> parseCount |
| | λ runParser reverseShowParseCount "aaaaaaaaaa00" |
| | Right ( "01" , "00" ) |
In these examples, the FilePackParser that we’re getting back when we call fmap (or (<$>) , which is the infix operator version of fmap ), is going to take whatever input we give it, and then pass that input along to the parser that we originally called fmap with, parseCount in this case.
Now that we’ve explored how our original fmap definition worked, let’s make a quick refactor to remove our unnecessary helper function:
| | instance Functor FilePackParser where |
| | fmap f parser = FilePackParser $ \input -> do |
| | (parsedValue, result) <- runParser parser input |
| | pure (f parsedValue, result) |
This version is less verbose and a bit easier to read for not having an extra function we have to keep track of. We’re no longer passing along a bunch of values for no reason, and instead we’re implementing the actual logic of fmap directly in its definition.
Next, let’s move on to defining an Applicative instance. While our Functor instance was broadly similar to the instance we defined for functions, our Applicative instance for FilePackParser will be a bit different.
We’ll start, as usual, by creating an instance and defining pure :
| | instance Applicative FilePackParser where |
| | pure a = FilePackParser $ \ s -> pure (a, s) |
Our pure function here is taking the entire input string that we get and moving it directly to the remainder, and setting the parsed value to the value passed into pure. If we take the computational view of our parser, where consuming some of the input is a side effect, then this definition of pure makes a lot of sense. We’re inserting a pure value into the parser, which means that we don’t have any side effects—we’re not consuming anything from the input.
Let’s stick with this computational view, where consuming values are side effects, as we start to think about how we can define (<*>) . In this view of the world, we have two computations. One of them will consume some of the input to give us a function, and the other will consume some of the input to give us a value that we can apply to that function. We need to return a new computation that combines both of those side effects and returns the result:
| | instance Applicative FilePackParser where |
| | pure a = FilePackParser $ \ input -> pure (a, input) |
| | f <*> s = FilePackParser $ \ input -> do |
| | (f', initialRemainder) <- runParser f input |
| | (a, finalRemainder) <- runParser s initialRemainder |
| | pure (f' a, finalRemainder) |
You can see here that the first thing we do is consume some of the input to get a function, f’ . We take the state, in this case the remainder of our input, and thread that through into our call to s . We return that remainder—the remainder after consuming the input of both parsers—along with the result of calling our function.
You’ll note here that order matters. Some types have Applicative instances that can be run in any order, or even in parallel, but for things like this where the order does matter, it’s conventional to keep the order of operations left-to-right, as we’ve done here.
Parsing with Applicatives
Now that we’ve built an Applicative instance, we have everything we need to extract a FilePack value, and to allow our users to build their own decoding tools based on our decoder. Before we move on to writing a Monad instance, let’s finish writing our decoders using what we have available so far from the Applicative type class. This will give you a chance both to see how far we can get with Applicative as well as an opportunity to see what restrictions we are under when we don’t have a Monad instance.
As you know, Applicative types give us a way of combining some computations in a particular way. The general pattern you’ll see for applicative parsers is we’re combining a computation that’s progressively building up a new fully parsed value with a second computation that’s progressively consuming parts of an unparsed value. This’ll be a bit easier to understand as we look at an example.
Since we’ve already written a few variations of it, let’s start by writing the part of our parser that consumes individual parts of our larger unparsed input. The extractValue parser will combine a lot of the functionality we’ve already written into a single parser called extractValue :
| | extractValue :: Decode a => FilePackParser a |
| | extractValue = FilePackParser $ \ input -> do |
| | when ( BS .length input < 4) $ |
| | Left "Input has less than 4 bytes, we can't get a segment size" |
| | |
| | let (rawSegmentSize, rest) = BS .splitAt 4 input |
| | segmentSize <- fromIntegral <$> bytestringToWord32 rawSegmentSize |
| | |
| | when ( BS .length rest < segmentSize) $ |
| | Left "not enough input to parse the next value" |
| | |
| | let (rawSegmentValue, rest') = BS .splitAt segmentSize rest |
| | |
| | case decode rawSegmentValue of |
| | Left err -> Left err |
| | Right a -> Right (a, rest') |
This parser follows the same pattern of many other parsing functions that we’ve already built. The first thing that we do is to try to get the size of the next input field by reading the field prefix and then taking that many bytes out of the input. If we don’t have enough input data, we generate an error. Next, we try to decode the segment that we’ve extracted, and we also return an error if that fails. Finally, we return the decoded value along with the remainder of the input that we didn’t use.
Before we move on, let’s try this out in ghci so that we can see it in action:
| | λ runParser (extractValue @ Word32 ) $ encodeWithSize @ Word32 12345 |
| | Right (12345, "" ) |
| | |
| | λ runParser (extractValue @ String ) $ encodeWithSize @ String "Parsing is fun" |
| | Right ( "Parsing is fun" , "" ) |
| | |
| | λ runParser (extractValue @ Word32 ) $ encodeWithSize @ String "Errors aren't fun" |
| | Left "Expecting 4 bytes but got 17" |
You can see in these examples that we can encode and decode single values now using our applicative decoder. One minor inconvenience here is that when we run the parser this way, we’re also getting back an empty string that’s leftover from our processing. To make our lives a bit easier, let’s add a helper function to make it easier for us to test our parsers as we’re working through some more examples in this chapter:
| | execParser :: FilePackParser a -> ByteString -> Either String a |
| | execParser parser inputString = |
| | fst <$> runParser parser inputString |
This function will allow us, and other users of our library, to more easily get a value out of an encoded input without needing to manually discard the leftover data that is included with runParser . As we’re testing our own code, this is just a small convenience, but for other users of our library this abstraction also serves to hide unnecessary implementation details from users who might not care about how we handle passing along the parse state.
The choice of how we want to order the arguments here can have a small but meaningful impact on how users will interact with our library. In fact, it’s common to see libraries like this provide named functions for both functions that take a parser first, followed by input, and functions that take input first followed by a parser. As you’re working through some of the examples in the rest of this chapter, think about how the ergonomics of parsing would be different if the order of arguments to execParser were flipped.
Before we look at how to decode larger data types, we need to define one. We’ll return to our FileData and FilePack examples shortly, but for the moment let’s create a small one-off record we can use to explore applicative style decoding:
| | data SomeRecord = SomeRecord |
| | { recordNumber :: Word32 |
| | , recordString :: String |
| | , recordTuple :: ( Word32 , String ) |
| | } deriving ( Eq , Show ) |
| | |
| | exampleRecord :: SomeRecord |
| | exampleRecord = SomeRecord 1 "two" (3, "four" ) |
| | |
| | packRecord :: SomeRecord -> ByteString |
| | packRecord SomeRecord {..} = |
| | encodeWithSize recordNumber |
| | <> encodeWithSize recordString |
| | <> encodeWithSize (fst recordTuple) |
| | <> encodeWithSize (snd recordTuple) |
Unlike some of our previous examples, we can’t just call extractValue here, because we don’t have a Decode instance defined for SomeRecord . We’re also dealing with a more complicated record type with a number of different fields. So, how do we go about decoding a value?
Our goal is to get each of the fields we need to reconstruct our record out of the encoded input, one by one, and pass them into the SomeRecord value constructor. At each step of the process, we’ll consume a bit more data from the unprocessed part of our input, and add that decoded value into our record.
We’ll call our new parser someRecordParser :
| | someRecordParser :: FilePackParser SomeRecord |
Rather than looking at how we can implement an entire parser for SomeRecord though, let’s take it a piece at a time. We’ll start by just parsing out the first field. As a refresher, remember that value constructors are functions that take in all of the elements in that type and return a new value, so the type of SomeRecord is:
| | SomeRecord :: Word32 -> String -> ( Word32 , String ) -> SomeRecord |
So, we’ll start with a Word32 value. You’ve already extracted some Word32 values out of an encoded string using extractValue and that’s exactly what we’re going to do here:
| | someRecordParser = SomeRecord |
| | <$> extractValue |
The first time you see this pattern you might have a hard time following the leap that we just made here, so let’s take a moment to slow down and make sure that we’ve fully understood what’s happening.
You’ll recall from several examples throughout the book the type of (<$>) is:
| | (<$>) :: Functor f => (a -> b) -> f a -> f b |
This might leave you wondering for a moment how we are able to say Some Record <$> extractValue when SomeRecord takes three arguments, but the first argument to (<$>) is a function of a single argument. The reason this work is our friend, currying. After all, we can rewrite the type of SomeRecord using some extra parentheses to be:
| | SomeRecord :: Word32 -> ( String -> ( Word32 , String ) -> SomeRecord ) |
So, SomeRecord really does fit the shape of a function (a -> b) it’s just that the b is itself a function with the type (String -> (Word32, String) -> SomeRecord) . This means that when we use (<$>) , what we’re going to end up with is a FilePackParser that parses a value and returns function:
| | SomeRecord <$> extractValue |
| | :: FilePackParser ( String -> ( Word32 , String ) -> SomeRecord ) |
Another way to look at this is that we’re taking the Word32 value that we get as a result of running our parser and applying that to SomeRecord . We’re keeping the leftover data that we didn’t consume when we parsed the Word32 value unmodified, so now we have a parser that will give us back a partially applied value constructor, plus the remainder of the input that wasn’t used to parse the value that we just applied.
Next up, we need to get a String . We already have a Decode instance defined for String , so we can use extractValue to get one of those too. The difference here is that when we started, SomeRecord was a normal function that we wanted to apply to a parsed value with fmap , but that left us with a parser. Of course, we just spent the last section building exactly what we need to handle this situation! The Applicative instance that we just defined will let us handle exactly this situation, with (<*>) :
| | someRecordParser = SomeRecord |
| | <$> extractValue |
| | <*> extractValue |
We can apply the same reasoning to using (<*>) that we did when we first used (<$>) . Remember that the type of (<*>) is:
| | (<*>) :: Applicative f => f (a -> b) -> f a -> f b |
In this case, a is String and b is ((Word32, String) -> SomeRecord) . If we think about what this is doing, using what we know about both Applicative in general and the specific implementation that we’ve built, you can see that we’re building up a new parser that will take some input and use it to run a computation that will generate a function. Next, we take the leftover input from running that computation and feed it into the extractValue parser to get a value, which we apply to the function we’ve just parsed.
The last parameter we need to pass into SomeRecord is again a little bit different. Instead of the plain single values we’ve passed in so far, we need to deal with a tuple: (Word32, String) . So, how do we get a FilePackParser (Word32, String) out of the input? It’s a compound value, and we can build it exactly the same way that we’ve been building our current parser: using (<$>) and (<*>) :
| | {-# LANGUAGE TupleSections #-} |
| | |
| | someRecordParser :: FilePackParser SomeRecord |
| | someRecordParser = SomeRecord |
| | <$> extractValue |
| | <*> extractValue |
| | <*> extractTuple |
| | where |
| | extractTuple :: FilePackParser ( Word32 , String ) |
| | extractTuple = (,) <$> extractValue <*> extractValue |
| TupleSections |
|---|
|
| The TupleSections extension has been available since GHC 6.12. It’s enabled by default in GHC2010 but you’ll need to enable it manually if you are using Haskell2010 . This is a safe extension that shouldn’t cause any problems with existing code. |
Now that we have a parser, we can hand it over to execParser to get a function that will directly transform some input into our desired output (or fail with an error message at the very least).
| | parseSomeRecord = execParser someRecordParser |
This gives us a nice function that we can use to evaluate any given input into a parsed output. It’s handy if we have a bunch of different records that we want to parse:
| | getSeveralRecords :: [ ByteString ] -> Either String [ SomeRecord ] |
| | getSeveralRecords = traverse (execParser someRecordParser) |
Another way to use execParser is by defining our actual parser directly inline, instead of defining someRecordParser as a FilePackParser separately. For example, we can rewrite it as:
| | someRecordParser :: ByteString -> Either String SomeRecord |
| | someRecordParser = execParser $ SomeRecord |
| | <$> extractValue |
| | <*> extractValue |
| | <*> ((,) <$> extractValue <*> extractValue) |
Now that we’ve figured out how to deal with extracting compound data types, we can apply these ideas directly to a couple of our Decode instances for tuples and FileData :
| | instance ( Decode a, Decode b) => Decode (a,b) where |
| | decode = execParser $ (,) <$> extractValue <*> extractValue |
| | |
| | instance Decode a => Decode ( FileData a) where |
| | decode = execParser $ FileData |
| | <$> extractValue <*> extractValue <*> extractValue <*> extractValue |
You’ll notice here that since decode should return an Either String value, we are able to again make use of execParser to get back a function that will take some input and immediately use it to try to decode the parser that we’ve defined in-line.
Now that we have everything we need to encode and decode FileData let’s write one more function to help us use ghci to manually test that we can correctly round-trip our data. If you aren’t familiar with it, round-trip testing is a term commonly used to describe tests that ensure encoding a value and then decoding it gets you back the same value that you originally started with.
| | testRoundTrip :: ( Encode a, Decode a, Show a, Eq a) => a -> IO () |
| | testRoundTrip val = |
| | case decode (encode val) of |
| | Left err -> |
| | putStrLn $ "Failed to round-trip value: " <> err |
| | Right roundTripVal |
| | | roundTripVal == val -> |
| | putStrLn "It works!" |
| | | otherwise -> do |
| | putStrLn "Round-trip failed!" |
| | putStrLn $ "expected: " <> show val |
| | putStrLn $ "got: " <> show roundTripVal |
| | |
| | runRoundTripTest :: IO () |
| | runRoundTripTest = |
| | testRoundTrip $ FileData |
| | { fileName = "c" |
| | , fileSize = 8 |
| | , filePermissions = 0644 |
| | , fileData = (0, "zero" ) :: ( Word32 , String ) |
| | } |
If you try this out in ghci you should see that “It Works!” We can now make use of our Applicative parser to more easily decode compound types, including our FileData type. Unfortunately, the work we’ve done so far doesn’t quite get us all the way to being able to fully decode an entire FilePack . In the next section, we’ll expand the capabilities of our parser to allow us to fully parse an entire archive.