0

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

1 Answers1

0

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?

  • You might want to use the token parser: 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.
  • Alternatively, you might want to transform the parsed list using a custom mapping function: sentence.map((list) => '${list[0]} ${list[1]}') yields '3 apples'.
Lukas Renggli
  • 8,754
  • 23
  • 46
  • Thank you for the clarification. What I'm trying to achieve is parsing a bit more complex sentence, converting all numbers expressed as words in their numeric counterpart. For example in _I need three bags of apples_ I want to recognize _three_ as _3_ and _bags of apples_. My first approach was to write a recognizer for all numbers, usign _map_ to convert them in digits, then _flatten_ the outermost result. Is there anything wrong with this idea? Since this doesn't work, I managed to flatten piece by piece the expression that might surround the numbers (in my language, of course). – Lorenzo Acerbo Oct 30 '20 at 16:55
  • Yes, you don't want to flatten the outermost result, only the individual parts. – Lukas Renggli Nov 01 '20 at 13:54