Data.Attoparsec.ByteString.Char8 provides character-oriented Attoparsec parsers for ASCII data stored in ByteString. It is useful when a parser needs convenient Char-based operations while consuming byte-oriented input. section 12.2.2
Use the module to build parsers incrementally:
- Parse fixed text with string and translate it into a value using (<$). section 12.2.2
- Read decimal numbers with decimal, whose result has an Integral type. section 12.2.2
- Recognize characters with satisfy, consume required runs with skipMany1, and read spans with takeWhile. section 12.2.2
- Combine optional comments and whitespace with char, choice, option, and recursive parser composition. section 12.2.2
Parsing a PNM header
A PNM parser chooses among P1 through P6 magic numbers, skips whitespace and comments, parses width and height with decimal, and conditionally reads maxVal. The resulting Header records the parsed values. section 12.2.2
Listing 12.23 A parser for PNM headers with Attoparsec
headerP :: Parser Header
headerP = do
skipWhitespace
magicNumber <-
choice #1
[ magicNumberP1P,
magicNumberP2P,
magicNumberP3P,
magicNumberP4P,
magicNumberP5P,
magicNumberP6P
]
skipWhitespace
width <- C8.decimal #2
skipWhitespace
height <- C8.decimal #2
maxVal <- do
if magicNumber == P1 || magicNumber == P4
then return Nothing
else Just <$> (skipWhitespace *> C8.decimal) #3
whitespace
return Header {..}
Inspect the complete headerP parser, including magic-number choice, decimal fields, conditional maxVal parsing, and final Header construction. section 12.2.2
