pBind
fun <I : Any, O, R, U : Any> pBind(parser: Parser<I, O, U>, transform: (O) -> Parser<I, R, U>): Parser<I, R, U>
Returns a Parser that runs parser and, on success, passes the output value to transform to obtain and immediately run a second parser.
pBind is the monadic bind (also known as flatMap) for parsers. Unlike pMap, the second parse step is not fixed in advance — it is chosen dynamically based on what the first parser produced. This makes it possible to write context-sensitive parsers whose structure depends on previously parsed values.
Behaviour
| Condition | Result |
|---|---|
| parser fails | Failure propagated from parser |
| parser succeeds, derived parser fails | Failure propagated from the derived parser |
| Both succeed | Success from the derived parser |
Type parameters
Example
// Parse a digit, then use its value to decide which character to match next.
val digit = pSatisfy<Char, Unit> { it.isDigit() }
val parser = pBind(digit) { d ->
// If the digit is '1', expect 'a'; otherwise expect 'b'.
val expected = if (d == '1') 'a' else 'b'
pSatisfy<Char, Unit> { it == expected }
}
val input = ParserInput.of("1a".toList(), Unit)
val result = parser(input) // Success('a', nextIndex=2, ...)Content copied to clipboard
Return
a Parser that sequences parser and the parser produced by transform.
Parameters
parser
the first parser to run.
transform
a function that receives the first parser's output and returns the next parser to run; should be side-effect-free.