liveBook · Manning

Char

As explained in Learn Haskell by Example

char is an Attoparsec parser that consumes a specified character and returns that character.

In Attoparsec, char parses one specified character and returns that character: char :: Char -> Parser Char. It is useful when a format contains a known delimiter or marker. section 12.2.2

Use char as a small building block inside larger parsers:

  • Require a marker with C8.char '%'; parsing fails when the next character is not '%'. section 12.2.2
  • Sequence it with another parser, such as C8.takeWhile (/= '\n'), to consume the remainder of a comment. section 12.2.2
  • Combine it with choice, option, or recursive whitespace parsers when the marker may occur between required fields. section 12.2.2

Parsing a PNM comment

comment :: Parser BS.ByteString comment = C8.char '%' >> C8.takeWhile (/= '\n') The parser consumes the leading percent sign, then reads characters until the newline. The percent sign is required; optional comment handling belongs to the surrounding parser. section 12.2.2

Listing 12.21 A parser for comments
comment :: Parser BS.ByteString
comment = C8.char '%' >> C8.takeWhile (/= '\n')     #1

View the complete comment parser listing. section 12.2.2

Here, char is a parser function, while Char is the Haskell character type used for values such as 'a', 'A', and '1'. section 2.2.1 section 12.2.2

How Learn Haskell by Example covers it

How deep it goes
Defines char's Parser type and demonstrates its sequencing with takeWhile, while deferring broader parser internals.
Examples
Uses a percent sign to begin a PNM comment and a newline to end its character scan.
What it assumes
Assumes basic Haskell types and parser combinators, while distinguishing the Char type from the char parser.
What you can do after
Apply it via Attoparsec to recognize required delimiter characters inside larger parsers.
How it connects
Connects char with Attoparsec Parser, takeWhile, satisfy, choice, option, and skipMany1.

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.