pOptional

fun <I : Any, O : Any, U : Any> pOptional(parser: Parser<I, O, U>): Parser<I, O?, U>

Returns a Parser that tries parser and, if it fails, succeeds with null at the same position.

pOptional is the zero-or-one combinator — it always succeeds. Use it to represent optional grammar elements.

Behaviour

ConditionResult
parser succeedsSuccess with the parsed value; index advanced
parser failsSuccess with null; index unchanged

Type parameters

  • I — the token type consumed by parser.

  • O — the output type of parser; null is returned when it is absent.

  • U — the user context type threaded through unchanged.

Example

val sign = pSatisfy<Char, Unit> { it == '+' || it == '-' }
val optionalSign = pOptional(sign)

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

val noSign = ParserInput.of("1".toList(), Unit)
val result2 = optionalSign(noSign) // Success(null, nextIndex=0, ...)

Return

a Parser that always succeeds with the parsed value or null.

Parameters

parser

the parser to attempt.

See also