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.

12.1 Writing a parser

12.1.1 Portable images from the past

12.1.2 How to parse a file

12.1.3 Composing effects

12.1.4 Choosing alternatively

12.1.5 Introducing monads

12.1.6 A discussion on monads

12.1.7 How to fail

12.2 Parsing on a bigger scale

12.2.1 An introduction to Attoparsec

12.2.2 Parsing images

12.2.3 Choosing between formats

12.2.4 Putting parsers together

Summary