liveBook · Manning

Data.Attoparsec.ByteString.Char8

As explained in Learn Haskell by Example

Data.Attoparsec.ByteString.Char8 is an Attoparsec module that provides character-oriented parsers for ASCII data stored in ByteString.

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

How Learn Haskell by Example covers it

How deep it goes
Explains parser composition through fixed strings, decimals, whitespace, comments, optionality, and a complete PNM header.
Examples
Demonstrates PNM magic numbers, whitespace, comments, decimal dimensions, and conditional maxVal fields.
What it assumes
Assumes familiarity with Attoparsec Parser and ByteString while demonstrating the required parser combinators through implementation.
What you can do after
Build a practical PNM header parser using character predicates, repetition, alternatives, optional parsing, and decimal conversion.
How it connects
Connects Attoparsec Parser with ByteString, parser combinators, Functor, Applicative, Monad, and PNM file formats.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.