Now that you know how to work with monads, let’s take a step further. In this chapter, you will learn how to use the parsec library.
The parsec library is an “industrial-strength, monadic parser combinator library for Haskell.”1 It’s used to create larger expressions by constructing parsers through a combination of different higher-order combinators. The main module of parsec is Text.Parsec, which provides ways to parse to Char data. The other module of parsec is Text.ParserCombinators.Parsec.
Parsec is useful when you are working with many user inputs and the users need to understand the error messages. The library may take different types of inputs, for example, Strings or tokens (strings with an assigned meaning) provided by an external program that performs lexical analysis (regarding Text.Parsec). The library also can be layered into a monad stack through the monad transformer that it provides (Text.ParserCombinators.Parsec). The monad transformer is useful in scenarios in which additional states of parsing need to be monitored.
For the moment, take this instruction as it is; you will learn about cabal in Chapter 26.
This example creates a parser that verifies whether the input contains matching parentheses.
Let’s analyze the functions that are being used. The function char takes as input a single character and returns the parsed character. Next (>>) is a function from the Monad class , which takes a constant function, which will be mapped over an instance of a monad and finally flatten the result (note that this function needs to return an instance of the monad itself). The function many applies a parser zero or more times and returns a list of the results of the parser. The eof parser succeeds only at the end of the input. Finally, the combinator (<|>) takes two parsers: if the left parser succeeds, then it applies this parser; otherwise, it tries the right parser.
You get two results: Right() indicates that there are matching parentheses, while Left... indicates a failure, detailing the error.
You can find some great documentation of parsec, including comprehensive examples, in [2]. Other relevant examples are in Chapter 16 of [3].
Summary
In this chapter, you learned what parsec is and when you can use it. Also, you examined a short example of using the functions of this package.
References
- 1.
D. Leijen and E. Meijer. “Parsec: Direct Style Monadic Parser Combinators for the Real World,” (2001)
- 2.
Parsec, a fast combinator parser, https://web.archive.org/web/20140528151730/http://legacy.cs.uu.nl/daan/parsec.html
- 3.
B. O’Sullivan, J. Goerzen, and D. B. Stewart, Real-World Haskell: Code You Can Believe In (O’Reilly Media, 2008)
- 4.
Parsec, https://wiki.haskell.org/Parsec
- 5.
parsec: monadic parser combinators, http://hackage.haskell.org/package/parsec