Monadic parser combinators in Haskell
A Parser combinator, as wikipedia describes it, is a higher-order function that accepts several parsers as input and returns a new parser as its output.
They can be very powerful when you want to build modular parsers and leave them open for further extension. But it can be tricky to get the error reporting right when using a 3rd party combinator library, and they tend to be slower in imperative languages. Nonetheless, it is an interesting cornerstone in functional programming and PLT, so it shouldn't hurt to learn about them by building one on our own.
We're going to start by writing a library that describes several tiny parsers and functions that operate on those parsers. Then, we're going to build some parsers to demonstrate the usefulness of our work.
To give you a small flash forward, here is a parser that accepts C-style identifiers, written with the help of our handy combinators:
It is recommended for you to have some basic understanding of:
- Monads in functional programming
This post is a derivative of two papers I had read recently (1, 2). If you like a denser reading, you can go through the papers instead. The full code for this blog can be found here on GitHub.
The Parser type
Before we begin to define combinators that act on parsers, we must choose a representation for a parser first.
A parser takes a string and produces an output that can be just about anything. A list parser will produce a list as it's output, an integer parser will produce Ints, a JSON parser might return a custom ADT representing a JSON.
Therefore, it makes sense to make Parser a polymorphic type. It also makes sense to return a list of results instead of a single result since grammar can be ambiguous, and there may be several ways to parse the same input string.
An empty list, then, implies the parser failed to parse the provided input. (1)
You might wonder why we return the tuple (a, String), not just a. Well, a parser might not be able to parse the entire input string. Often, a parser is only intended to parse some prefix of the input, and let another parser do the rest of the parsing. Thus, we return a pair containing the parse result a and the unconsumed string subsequent parsers can use.
We could have used the type keyword let Parser be an alias for String -> [(a, String)], but having a unique data type lends us the ability to instantiate it as a typeclass, which is something we'll do later on.
We can start by describing some basic parsers that do very little work. A result parser always succeeds in parsing without consuming the input string.
The parser zero will always fail by returning an empty list.
item unconditionally accepts the first character of any input string.
Let's try some of these parsers in GHCi:
Building parsers on demand
The basic parsers we defined above are of very little use. Ideally, we would want parsers that accept input strings that satisfy certain constraints. Say we want a parser that consumes a string if its first character satisfies a predicate. We can generalize this idea by writing a function that takes a (Char -> Bool) predicate and returns a parser that only consumes an input string if its first character returns True when supplied to the predicate.
The simplest solution for this would be:
However, since we already have an item parser that unconditionally extracts the first character from a string, we could use this as an opportunity to create a basic parser combinator.
Before writing a combinator, we must first instantiate Parser as a Monad. (2)
The bind operation takes a Parser a (p) and a function a -> Parser b (f), and returns a Parser b. The idea is to apply p, if it fails, then we have an empty list which results in concat [] = . If p successfully parses inp into one or more possible parse results, we apply f to each of the results to get corresponding Parser bs and then apply those to the rest of the input.
With this new extension, our sat parser can be re-written as:
Now we can use the sat combinator to describe several useful parsers. For example, a char parser that only consumes a string beginning with a specific character.
A parser for ASCII digits:
And similarly small but useful parsers:
Now that we have upper, lower and digit this opens up new possibilities for combinations:
- An alphabet parser that accepts a char that is consumable by either upper or lower.
- An alphanumeric parser that accepts a char, either alphabet or digit.
Clearly, an or' combinator that captures this recurring pattern will come in handy.
Let us begin by describing a plus combinator that concatenates the result returned by two parsers:
Haskell has a MonadPlus typeclass defined in the prelude like so:
mzero represents failure, and mplus represents combination of two monads. Since Parser is already a monad, we can instantiate the MonadPlus typeclass to enforce this idea:
The or' combinator can then be:
In fact, the Alternative typeclass already defines this functionality with the choice (<|>) operator:
Finally, we can return to the letter and alphanum parsers:
We can now take them for a spin in GHCi:
As an aside, we can use the sequencing (>>) operator to write more concise code at times. Consider the function string for example, where string "foo" returns a parser that only accepts strings which begin with "foo".
Using >>= notation, we would have had to write:
Using the do notation
Haskell provides a handy do notation for readably sequencing monadic computations. This is useful when composing monadic actions becomes a bit gnarly looking. Consider this example that composes the outputs of several parsers:
Using the do notation, the above code snippet becomes:
Moving forward, we will prefer the do notation over >>= wherever it improves readability.
Combinators for repetition
You may be familiar with the regex matchers + and *. a* matches zero or more occurrences of the letter 'a', whereas a+ expects one or more occurrences of the letter 'a'.
We can represent the * matcher as a combinator like so:
Looks decent, but when run in GHCi, it fails to produce the expected result:
If you try to work out the application of this parser by hand, you'll notice a flaw in our base case: In the final recursive call, when the input string is "", x <- p fails, and we short circuit to return .
To handle this scenario, we can use our or' combinator:
And we're golden:
If the use of <|> is still confusing to you, try working it out on paper.
Analogous to the regex + matcher, we can write a many1 combinator that accepts one or more occurrences of an input sequence. Piggybacking off of many', this can be simply written as:
Parsing a list of identifiers
If you haven't realized by now, we've built some combinators capable of parsing regular languages. Circling back to the beginning of this post, here is a combinator that parses a valid C-style identifier:
To make it even more concise, we can define a then' combinator which combines the result produced by two parsers using a caller provided function.
A thenList combinator can then combine to parse results of type a and [a] using (:).
Now our identifier parser becomes even shorter:
Now, lets take our combinations a step further. Say we want to parse a list of comma-separated identifiers, Here is one way to do that:
A token-separated list of items is a commonly occurring pattern in language grammar. As such, we can abstract away this idea with a sepBy combinator:
Now, what if the list of identifiers was enclosed in braces like in an array? We can define another combinator, bracket, to parse strings enclosed within specific sequences.
Sequencing operators can be used to write bracket in a slightly more elegant manner:
Using this, our parser for a list of items can be written as:
Let's test this implementation in GHCi:
Parsing natural numbers
Since our parsers are polymorphic, we can return a parse result containing an input string's evaluated value. Here is a parser that consumes and evaluates the value of a natural number:
A natural number is one or more decimal digits, which we then fold to produce a base 10 value. Alternatively, we can use the builtin read to implement nat:
As you may already have noticed, the parsers we've written so far aren't great at dealing with whitespace.
Ideally, we should ignore any whitespace before or after tokens. Generally, it is a tokenizer's job to handle whitespaces and return a list of tokens that the parser can then use. However, it is possible to skip a tokenizer completely when using combinators.
We can define a token combinator that takes care of all trailing whitespace:
And a parse' combinator that removes all leading whitespace:
The parse' combinator is applied to the final parser once to ensure there is no leading whitespace. The token combinator consumes all trailing whitespace, hence ensuring there is no leading whitespace left for the subsequent parsers.
We can now write parsers that disregard whitespace:
At this point, we have atomic parsers that can be plugged in several places. One such place can be an arithmetic expression evaluator:
An expression parser
Finally, to demonstrate the usefulness of combinators we have defined so far, we build a basic arithmetic expression parser. We will support the binary + and - operators, parenthesized expressions and integer literals. By the end, we will have an eval function that can evaluate expressions like so:
Spin up GHCi, and there we have it:
Our parser is decent, but it can be refactored a little further. An expression is a list of parenthesized expressions and integer literals separated by + or -.
As it turns out, parsing a list of token delimited items is a common pattern captured by the chainl1 combinator:
And with that, we have a monadic expression parser composed of several tiny and modular parsers. As an exercise, you can extend this parser and add more operators such as multiplication, division, and log.
There are already several parser combinator libraries for many languages, as you may have guessed. Parsec in particular, is the most commonly used one among Haskell programmers. Here are more resources for you to chew on:
- Monadic Parser Combinators
- Functional Pearls - Monadic Parsing in Haskell
- Microsoft Research - Direct style monadic parser combinators for the real world
The first two should feel very familiar if you've followed the post so far. The 3rd is a paper that attempts to provide a better alternative technique for parsing using monads.
At this point, parser combinators have become another tool in your functional programming arsenal. Go forth and write some killer parsers!
1. In most implementations, the parse result is a functor that can store an error message in case the parser fails.
2. In order to instantiate Parser as a Monad in Haskell, we also have to make it an instance of Functor and Applicative: