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

ConditionResult
parser failsFailure propagated from parser
parser succeeds, derived parser failsFailure propagated from the derived parser
Both succeedSuccess from the derived parser

Type parameters

  • I — the token type consumed by both parsers.

  • O — the output type of parser; passed to transform.

  • R — the output type of the parser returned by transform.

  • U — the user context type threaded through unchanged.

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, ...)

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.

See also