liveBook · Manning

Parser choice

As explained in Functional Programming in Scala, Second Edition

Parser choice is a combinator that succeeds when either of two alternative parsers succeeds.

Parser choice combines two alternative parsers into one parser that succeeds when either alternative succeeds. Its infix form, |, keeps alternatives readable. section 9.1

The alternatives can parse the same result type. Trying string("abra") | string("cadabra") accepts either input and returns the matching string. section 9.1

Choosing between strings

val p = string("abra").or(string("cadabra")) p.run("abra") == Right("abra") p.run("cadabra") == Right("cadabra") section 9.1

extension [A](p: Parser[A]) def or(p2: Parser[A]): Parser[A]

Browse the generic or combinator signature for combining parsers with the same result type. section 9.1

string("abra").or(string("cadabra")).run("abra") == Right("abra")
string("abra").or(string("cadabra")).run("cadabra") == Right("cadabra")

Browse executable alternatives showing successful results for each branch. section 9.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the combinator, gives its generic API, and demonstrates successful alternatives without detailing failure selection or error merging.
Examples
Demonstrates alternatives with "abra" and "cadabra", then combines a choice with listOfN for repeated parsing.
What it assumes
Assumes basic parsers, string parsers, parser results, and extension-method syntax.
What you can do after
Apply it via the parser API to accept one of several alternatives and preserve the successful result.
How it connects
Connects parser choice to parser combinators, string parsers, parser results, and repeated 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.