pOptional
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
| Condition | Result |
|---|---|
| parser succeeds | Success with the parsed value; index advanced |
| parser fails | Success with null; index unchanged |
Type parameters
O — the output type of parser;
nullis 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, ...)Content copied to clipboard
Return
a Parser that always succeeds with the parsed value or null.
Parameters
parser
the parser to attempt.