I am trying to parse a sentence and, at the same time, convert numbers to their digit representation.
As a simple example I want the sentence
three apples
parsed and converted to
3 apples
With this code simple code I can actually parse the sentence correctly and convert three in 3, but when I try to flatten the result, 3 is reverted back to three.
Parser three() => string('three').trim().map((value) => '3');
Parser apples() => string('apples').trim();
Parser sentence = three() & apples();
// this produces Success[1:13]: [3, apples]
print(sentence.parse('three apples'));
// this produces Success[1:13]: three apples
print(sentence.flatten().parse('three apples'));
Am I missing something? Is flatten behavior correct?
Thanks in advance L
Yes, this is the documented behavior of flatten: It discards the result of the parser, and returns a sub-string of the consumed range in the input being read.
From the question it is not clear what you expect instead?
sentence.token().parse('three apples')
. This will yield a Token
object that contains both, the parsed list [3, 'apples']
through Token.value and the consumed input string 'three apples'
through Token.input.sentence.map((list) => '${list[0]} ${list[1]}')
yields '3 apples'
.