HeadlinesBriefing HeadlinesBriefing.com

Parser Combinators Explained with Examples

Hacker News •
×

Parser combinators are functions that take an input string and return a parsed value along with the remaining unparsed string. A Parser<T> is defined as (input: string) => [T, string]. For example, p Integer parses "10 20 30" into the number 10 and the remainder " 20 30". p Hello extracts "Hello" from "Hello 100", leaving " 100". p Ignore Whitespace consumes spaces, returning " " and "100". p Integer then parses "100" into the number 100 and an empty string.

Sequencing combinators like p Seq allow combining parsers: p Seq(p Hello, p Ignore Whitespace, p Integer) parses "Hello 100" into the tuple ["Hello", null, 100]. The p Map combinator transforms parsed values, such as converting ["Hello", null, 100] into {greeting: "Hello", who: 100}. Similarly, p Seq(p Number, p Semicolon) parses "10;20;30;" into a list of numbers by repeatedly applying the parser to consume each number-semicolon pair.

The article also illustrates parsing network ping output, showing how structured data can be extracted from raw text using these combinators. Fold and unfold operations demonstrate how parsers can reduce or reconstruct values, such as summing a list or converting "Hello 100" to ["Hello", " ", 100] and vice versa.

Source: Hacker News · Summarized by HeadlinesBriefing