liveBook · Manning

String parser

As explained in Functional Programming in Scala, Second Edition

A string parser is a parser combinator that recognizes a specified complete string and returns it as its result.

A string parser recognizes a specified string and returns that string on success. It is a primitive Parser[String]: running it produces either a parse error or the recognized value, rather than only a yes/no answer. section 9.1

def string(s: String): Parser[String]

The constructor takes the literal to recognize and produces a parser whose result type is String. section 9.1

Choosing between literals

A literal parser can be combined with choice. The parser below accepts either "abra" or "cadabra" and returns whichever alternative matched, making small grammars readable before introducing larger examples. section 9.1

String parsing supports derived combinators. A character parser can be expressed by parsing its one-character string and mapping the result to Char. Repetition can then collect matched strings, while map transforms successful results without changing failures. section 9.2 section 9.1

The primitive checks the requested literal at the current input location. On a match it succeeds with the literal and its consumed length; on the first mismatch it reports an error at the corresponding advanced location. Full-document parsing is added separately with an end-of-input parser. section 9.6 section 9.8

Literal parsers become grammar punctuation and keywords. For example, JSON parsing uses them for brackets, commas, null, true, and false; a token helper combines a literal with whitespace handling and delayed commitment for alternatives. section 9.8

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the constructor, derives char from it, and implements matching, consumption length, and mismatch errors.
Examples
Uses "abra" and "cadabra" alternatives, character parsing, and JSON punctuation and literal tokens.
What it assumes
Introduces parsing from simple letter strings while assuming enough Scala to read parameterized parser signatures.
What you can do after
Build it from scratch by implementing literal matching that returns consumed length or a located parse error.
How it connects
Connects to Parser, char, map, choice, whitespace, end-of-input, and JSON parsing.

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.