liveBook · Manning

Parser combinator library

As explained in Functional Programming in Scala, Second Edition

A parser combinator library is a software library whose compositional operations create parsers from elementary and other parsers.

A parser combinator library builds parsers by composing elementary parsers with other parsers and reusable combinators. A parser consumes unstructured data—such as text or a stream of symbols, numbers, or tokens—and produces a structured representation. Even a parser that recognizes one character can become part of a larger parser. section 9.0

The approach differs from a parser generator library: instead of constructing a parser from a grammar specification, it assembles one directly from primitive operations and combinators. Algebraic design guides the process: define an interface and its laws first, then choose representations that support them. Interactions among operations, sample uses, and implementation difficulties refine the API. section 9.0 section 9.8

Common combinators support progressively richer parsers:

  • many parses zero or more repetitions and returns a list; many1 requires one or more repetitions. section 9.8
  • The product combinator, also written as **, runs two parsers in sequence and returns their results as a tuple. section 9.8
  • map, map2, and flatMap construct composite parsers; flatMap additionally supports context-sensitive parsing. section 9.8
  • label and scope attach information that improves errors when parsing fails. section 9.8

From records to trees

A parser can turn a comma-separated file into a list of records and fields, or transform an XML or JSON document into a tree-like structure. The same library can begin with a single-character parser and combine it into these larger structures. section 9.0

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains primitives, repetition, sequencing, mapping, context sensitivity, errors, and interface design, stopping short of implementation details.
Examples
Uses character recognition, comma-separated files, XML, JSON, repetition, sequential products, and context-sensitive parsing.
What it assumes
Assumes only the distinction between unstructured input and structured output, while introducing parser composition from elementary operations.
What you can do after
Builds composite and context-sensitive parsers with repetition, sequencing, mapping, and improved failure labels.
How it connects
Connects parsers with parser generator libraries, algebraic design, combinators, structured data, and error messages.

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.