pChoice

fun <I : Any, O, U : Any> pChoice(parsers: List<Parser<I, O, U>>): Parser<I, O, U>

Returns a Parser that tries each parser in parsers in order, returning the first success.

pChoice is the n-ary generalisation of pOr: it reduces the list with pOr, so its failure and precedence semantics are identical. When all parsers fail the result is the failure that reached the furthest index.

An empty parsers list always fails with "No alternatives".

Behaviour

ConditionResult
parsers is emptyFailure — "No alternatives"
First matching parser succeedsSuccess from that parser
All parsers failFailure from whichever reached the furthest index

Type parameters

  • I — the shared token type consumed by all parsers.

  • O — the shared output type; all parsers must produce the same type.

  • U — the user context type threaded through unchanged.

Example

val parser = pChoice(listOf(
pSatisfy<Char, Unit> { it == 'a' },
pSatisfy<Char, Unit> { it == 'b' },
pSatisfy<Char, Unit> { it == 'c' },
))

val input = ParserInput.of("b".toList(), Unit)
val result = parser(input) // Success('b', nextIndex=1, ...)

Return

a Parser that succeeds with the first matching alternative.

Parameters

parsers

the ordered list of alternatives to try.

See also


fun <I : Any, O, U : Any> pChoice(vararg parsers: Parser<I, O, U>): Parser<I, O, U>

Vararg overload of pChoice.