So far you’ve successfully unpacked a single FileData value using your Applicative parser, but to unpack an entire archive we need to support being able to decode an entire list of values. In theory, this shouldn’t be too hard, as we’ve been working with lists since the first chapter of this book, but the fact that we’re now dealing with parsers instead of plain lists means we need to think a bit differently about how we build support for decoding values.
Fundamentally, what we’d like to do is to have our user give us a way of parsing a single element, and we’d then like to use that parser to parse as many elements as there are in the input we’re given.
One way to do this is build our own recursive parser that will call extractValue to get each element of our list, as long as we have some input. Let’s write a function called extractValues that will handle this for us:
| | {-# LANGUAGE OverloadedStrings #-} |
| | |
| | extractValues :: Decode a => FilePackParser [a] |
| | extractValues = FilePackParser $ \ input -> |
| | if BS .null input |
| | then Right ( [] , "" ) |
| | else do |
| | (val, rest) <- runParser extractValue input |
| | (tail, rest') <- runParser extractValues rest |
| | pure (val:tail, rest') |
In this function we test to see if we’re at the end of the input, and if so, we return an empty list. This is our base case. Otherwise we try to extract the next element, which will be the head of the list, and then recursively parse the remainder of the input. Aside from the small detail that we’re running inside of a FilePackParser , this resembles a lot of other direct recursive functions that we’ve built throughout the book. This works, and we can test it out in ghci to see it in action:
| | λ execParser (extractValues @ Word32 ) $ encode @[ Word32 ] [1..10] |
| | Right [1,2,3,4,5,6,7,8,9,10] |
The first problem with this approach is that it’s not very flexible. We’re using extractValue to parse values, but that only works as long as we have a Decode instance. If we want to decode a list of values using some other parser, we’d need to define a brand new Decode instance, possibly using a newtype wrapper, or we’d need to write a new version of extractValues .
As a concrete example, let’s imagine that we have a parser named decodeEven that will extract Word32 values that are even, but will fail on odd values:
| | parseEven :: FilePackParser Word32 |
| | parseEven = FilePackParser $ \ input -> do |
| | (n, rest) <- runParser extractValue input |
| | when (odd n) $ |
| | Left $ show n <> ": value is odd" |
| | pure (n, rest) |
There’s an easy way that we can deal with this without needing to change extractValues too much: instead of hard-coding extractValue we can pass in the parser that we want to use. Since we’re not always calling extractValue , let’s also rename our function to something a little bit more meaningful:
| | parseMany :: FilePackParser a -> FilePackParser [a] |
| | parseMany parseElement = FilePackParser $ \ input -> |
| | if BS .null input |
| | then Right ( [] , "" ) |
| | else do |
| | (resultHead, rest) <- runParser parseElement input |
| | (resultTail, rest') <- runParser (parseMany parseElement) rest |
| | pure (resultHead : resultTail, rest') |
Now, we can turn any arbitrary parser for a single element into a list parser that will consume all of the input and give us back a list of values:
| | λ execParser (parseMany @ Word32 parseEven) $ encode @[ Word32 ] [2,4..10] |
| | Right [2,4,6,8,10] |
And, we can get some useful errors out if something goes wrong:
| | λ execParser (parseMany @ Word32 parseEven) $ encode @[ Word32 ] [1..10] |
| | Left "1: value is odd" |
This approach to parsing a list of values is a good one, so long as we always want to consume the entire input when we parse. Unfortunately, sometimes we’ll run into situations where we need to consume an unknown number of inputs into a list without consuming the entire input. To handle this kind of situation we only have one option: keep parsing data until we encounter an error, and then move on.
One way to handle this is to continue to modify our existing function so that instead of passing back a failure when our element parser fails, we instead return an empty list:
| | parseMany :: FilePackParser a -> FilePackParser [a] |
| | parseMany parseElement = FilePackParser $ \ input -> |
| | case runParser parseElement input of |
| | Left _err -> |
| | pure ( [] , input) |
| | Right (val, rest) -> do |
| | (tail, rest') <- runParser (parseMany parseElement) rest |
| | pure (val:tail, rest') |
This is fine, it will let us parse lists the way that we want, but let’s consider a similar problem. Imagine if, instead of a list, we wanted to parse an optional value. We might follow the same pattern we just used for decoding lists and write a function called extractOptional that returns Nothing instead of an empty list if we fail to parse a missing value:
| | extractOptional :: FilePackParser a -> FilePackParser ( Maybe a) |
| | extractOptional parseElement = FilePackParser $ \ input -> |
| | case runParser parseElement input of |
| | Left _err -> pure ( Nothing , input) |
| | Right (val, rest) -> pure ( Just val, rest) |
It turns out that both of these functions are special cases of a more general problem that comes up regularly when we’re dealing with things like parsers: trying one parser, and if it fails then trying an alternative parser. This pattern is common enough that it’s defined by the Alternative type class in Control.Applicative in base .
The Alternative type class is defined in base like this:
| | class Applicative f => Alternative f where |
| | empty :: f a |
| | (<|>) :: f a -> f a -> f a |
| | some :: f a -> f [a] |
| | many :: f a -> f [a] |
| | {-# MINIMAL , (<|>) #-} |
Alternative gives us a way to combine two different Applicative values, and it’s frequently used when building parsers to represent the idea of choice between two options. If the first option succeeds, it’s returned, otherwise the second option is returned. Before we dive into what that means for FilePackParser , let’s use ghci to look at a couple of examples of Alternative instances that are already defined for us.
The empty function gives us back an “empty” value. The precise definition of empty can vary a lot depending on the type of thing we’re dealing with. For example, the empty value of Maybe is Nothing :
| | λ empty @ Maybe |
| | Nothing |
For lists, the empty value is, intuitively, an empty list:
| | λ empty @ [] |
| | [] |
Another example of something with an Alternative instance is IO . This case is a little bit different, because the value we get back from an empty IO is an exception. This might seem counterintuitive at first, but shortly we’ll look at why this ends up being convenient in practice.
| | λ empty @ IO |
| | *** Exception : user error (mzero) |
The other required function we need to define for Alternative is the (<|>) operator. This operator will return the “sum” or “combination” of its left and right values. As with empty , the precise definition can vary depending on the specific type we’re looking at. For lists, it simply combines the two lists:
| | λ [1,2,3] <|> [] |
| | [1,2,3] |
| | λ [1,2,3] <|> [4,5,6] |
| | [1,2,3,4,5,6] |
| | λ [] <|> [4,5,6] |
| | [4,5,6] |
| | λ [] <|> [] |
| | [] |
On the other hand, Maybe defines (<|>) to be the first non- Nothing value, if there is one:
| | λ Just "Hello" <|> Just "World" |
| | Just "Hello" |
| | λ Just "Hello" <|> Nothing |
| | Just "Hello" |
| | λ Nothing <|> Just "World" |
| | Just "World" |
| | λ Nothing <|> Nothing |
| | Nothing |
The definition of (<|>) for IO is similar. It returns the value of the first IO action that did not raise an exception:
| | λ putStrLn "Hello" <|> putStrLn "World" |
| | Hello |
| | λ ioError (userError "exception" ) <|> putStrLn "World" |
| | World |
| | λ putStrLn "Hello" <|> ioError (userError "exception" ) |
| | Hello |
| | λ ioError (userError "exception one" ) <|> ioError (userError "exception two" ) |
| | *** Exception : user error (exception two) |
For FilePackParser we can define our own instance that’ll behave similarly to the IO instance: we’ll return the first non-exception value we encounter. Of course, we don’t have to worry about IO errors, only situations where our parser returns a Left value. Like IO , we’ll consider an empty parser to be an error.
| | import Control.Applicative |
| | |
| | instance Alternative FilePackParser where |
| | empty = FilePackParser $ const ( Left "empty parser" ) |
| | parserA <|> parserB = FilePackParser $ \ s -> |
| | case runParser parserA s of |
| | Right val -> Right val |
| | Left errA -> runParser parserB s |
Although our Alternative instance here isn’t much more complicated than a case statement, we can use it to rewrite a much nicer version of both extractOptional and parseMany .
We can rewrite extractOptional as a short one-line function:
| | extractOptional :: FilePackParser a -> FilePackParser ( Maybe a) |
| | extractOptional p = Just <$> p <|> pure Nothing |
Or, in pointfree style:
| | extractOptional = (<|> pure Nothing ) . fmap Just |
Our new version of parseMany similarly becomes a short one-line function, but now we have a choice to make. In the very first version of our list parsing function, we wrote a list parser that would consume all of the input data. It would also helpfully give us an error if our parser failed, which can be highly desirable if we know that we’re expecting at least some value. When we refactored that code to allow only parsing as much input as was available, we lost the ability to also ensure that we got at least one value. So, do we want to write a function that parses some (one or more) values, or a function that parses as many (zero or more) values as are available?
Now that we have an Alternative instance making it easier for us to be more expressive, we don’t have to pick. Each of these new functions can be written as a one-liner. So, let’s write them. parseSome will parse at least one element, up to as many as are available in the input. parseMany will parse as many as are available, but will successfully return an empty list if nothing can be parsed.
| | parseSome :: FilePackParser a -> FilePackParser [a] |
| | parseSome p = (:) <$> p <*> parseMany p |
| | |
| | parseMany :: FilePackParser a -> FilePackParser [a] |
| | parseMany p = parseSome p <|> pure [] |
You’ll notice that these two functions are mutually recursive . parseSome parses the head of the list, and then gets the tail of the list by calling parseMany . We define parseMany by first trying to parse one or more elements with parseSome , and if that fails then giving up and returning an empty list. Although we haven’t seen this sort of mutual recursion across functions much, if you try it out you’ll see that thanks to laziness it works exactly as we’d expect.
Let’s load these new functions into ghci and watch them in action:
| | λ someEvens = encode @[ Word32 ] [2,4,6,8] |
| | λ someNums = encode @[ Word32 ] [1,2,3,4,6,8] |
| | |
| | λ execParser (extractOptional parseEven) someEvens |
| | Right ( Just 2) |
| | λ execParser (extractOptional parseEven) someNums |
| | Right Nothing |
| | |
| | λ execParser (parseSome parseEven) someEvens |
| | Right [2,4,6,8] |
| | λ execParser (parseSome parseEven) someNums |
| | Left "1: value is odd" |
| | |
| | λ execParser (parseMany parseEven) someEvens |
| | Right [2,4,6,8] |
| | λ execParser (parseMany parseEven) someNums |
| | Right [] |
Our functions work great, and thanks to Alternative they were easy to write. It turns out that we didn’t actually need to write these functions at all. Our parseSome and parseMany functions are precisely the implementations of some and many that the Alternative type class defines for us when we create a new instance, and extractOptional is just our own implementation of the optional function that’s already defined for us in Control.Applicative :
| | λ :t some |
| | some :: Alternative f => f a -> f [a] |
| | λ :t many |
| | many :: Alternative f => f a -> f [a] |
| | λ :t optional |
| | optional :: Alternative f => f a -> f ( Maybe a) |
Using our new Alternative instance we can now write a Decode instance for lists, getting us a step closer to our FilePack decoder:
| | instance {-# OVERLAPPABLE #-} Decode a => Decode [a] where |
| | decode = execParser (many extractValue) |
Now that we’re able to decode an entire list of files, we can fully decode a FilePack :
| | testDecodeValue |
| | :: ByteString |
| | -> Either String |
| | ( FileData String |
| | , FileData [ Text ] |
| | , FileData ( Word32 , String ) |
| | ) |
| | testDecodeValue = execParser $ (,,) |
| | <$> extractValue |
| | <*> extractValue |
| | <*> extractValue |
You can test this yourself using the testEncodedValue function you wrote in the last chapter.
So, you can see that we’ve been able to write a complete parser thanks to Applicative and a little help from Alternative . A lot of the time these two type classes are all you need to write a parser. In some cases though, Applicative doesn’t give us quite enough expressive power. In those cases, we need to also go ahead and stay true to the “Monadic Parser” name and implement a Monad instance as well. In the next section, we’ll add a Monad instance and you’ll see some of the benefits that you get from monadic parsing over applicative parsing.