pOr

fun <I : Any, O, U : Any> pOr(first: Parser<I, O, U>, second: Parser<I, O, U>): Parser<I, O, U>

Returns a Parser that tries first and, if it fails, tries second at the same position.

pOr implements ordered choice: first is always preferred. second is only attempted when first fails, and always against the original input position, never against input that first may have partially consumed.

When both parsers fail, the failure with the greater Failure.index is returned, as it represents the furthest point reached in the input. If both fail at the same index, the failure from second is returned.

Behaviour

ConditionResult
first succeedsSuccess from first
first fails, second succeedsSuccess from second
Both failFailure from whichever reached the furthest index

Type parameters

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

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

  • U — the user context type threaded through unchanged.

Example

val digit = pSatisfy<Char, Unit> { it.isDigit() }
val letter = pSatisfy<Char, Unit> { it.isLetter() }
val digitOrLetter = pOr(digit, letter)

val input = ParserInput.of("a1".toList(), Unit)
val result = digitOrLetter(input) // Success('a', nextIndex=1, ...) via letter

Return

a Parser that succeeds if either alternative matches.

Parameters

first

the parser to try first.

second

the parser to try if first fails.

See also