liveBook · Manning

Char

As explained in Functional Programming in Scala, Second Edition

char is a parser combinator that recognizes a specified single character and returns that character.

char is the smallest useful parser combinator: it recognizes one specified character and returns that character when the input matches. Its result type is Parser[Char], preserving the parsed value instead of reducing success to a yes-or-no answer. Running the parser produces either a ParseError or the returned character. section 9.1

Recognizing a character

A parser for 'a' can be run against the corresponding one-character string: char('a').run("a") == Right('a'). The parser succeeds only for the specified character; longer or different input does not satisfy this primitive parser. Once string and map exist, char can be defined as: def char(c: Char): Parser[Char] = string(c.toString).map(_.charAt(0)). section 9.1 section 9.2

trait Parsers[ParseError, Parser[+_]]:      #1
 
  extension [A](p: Parser[A]) def run(input: String): Either[ParseError, A]
 
  def char(c: Char): Parser[Char]           #2

The parser algebra places char beside run: char constructs a Parser[Char], while run executes it against a String and reports Either[ParseError, Char]. section 9.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines recognition, result typing, execution, and a string-map implementation, but defers parser and error representations.
Examples
Uses char('a'), execution against "a", and the equivalent string(c.toString).map(_.charAt(0)) definition.
What it assumes
Assumes Scala character and string syntax while introducing Parser, ParseError, and parser execution through concrete examples.
What you can do after
Build it from scratch as a Parser[Char] primitive or derive it from string and map.
How it connects
Connects Parser with run, ParseError, String, string, and map.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.