Parser Combinators

244 points · 85 comments on HN · read original →

Points and comments are a snapshot, not live.

Parser combinators offer a more powerful and composable alternative to regular expressions for parsing tasks.

The article introduces parser combinators as a functional approach to parsing, defining a Parser<T> as a function from string to [T, string]. It demonstrates building complex parsers by combining simpler ones through sequencing (pSeq), mapping (pMap), and repetition (pRepeat). The tutorial walks through constructing a parser for ping command output, parsing headers, packets, and statistics. Key concepts include partial parsers that consume portions of input, chaining parsers sequentially, and handling whitespace. The approach is presented as more readable and maintainable than regex for structured data parsing, with the final example parsing ICMP ping output into structured objects.

The article uses visual code examples showing parser composition step by step, from basic integer parsers to complex structured data extraction from network diagnostics output.

What commenters are saying

Commenters largely praised parser combinators as a pedagogical tool for understanding both parsing and functional programming concepts like curried functions and partial application. One commenter noted that the type signature "Parser<T> = (input: string) => [T, string]" implies parsers always return a T rather than potentially failing, suggesting Either<Error, [T, string]> would be more accurate. The author acknowledged this limitation, citing parsimmon library's exception-throwing approach.

A recurring point of discussion was the article's multi-page slide format, with several commenters finding it harder to navigate than a single scrollable page. The classic parser poem "A parser for things is a function from strings to lists of pairs of things and strings" was shared multiple times. A concrete suggestion was made to parse packet metadata as generic key-value pairs rather than hardcoded fields.