12 Parsing pixel data
This chapter covers
- Writing parsers for text from scratch
- Combining effectful actions
- The theory behind functors, applicatives, and monads
- Building parsers for binary data with the Attoparsec library
In previous chapters, we tackled the task of reading data in a certain way, be it lines of a file or more intricate formats, like CSV. For our purposes, we have created custom functions for reading this data, tailor-made to the task at hand. However, this is not what we typically do in these situations. Usually, no matter what language we are using, we would construct some kind of parser to do this. In Haskell, the development of parsers is an almost unique experience in how cleanly they compose, to build a bigger parser from simple building blocks.
In this chapter, we will write our own simplified parser library to read PNM files, a family of simple image file formats, which will not only teach us how to compose effectful actions but also how to gracefully handle any errors and failures we might run into on the way. We do this by using applicatives and monads, and we will understand how they work and why they are an essential building block in Haskell. After that, we will get to know Attoparsec, a widely used parser combinator library, which will help us to create performant parsers for image files.