0

我正在尝试解析一个句子,同时将数字转换为它们的数字表示。

作为一个简单的例子,我想要句子

三个苹果

解析并转换为

3个苹果

使用此代码简单代码,我实际上可以正确解析句子并将转换为3,但是当我尝试将结果展平时,3恢复为

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'));

我错过了什么吗?展平行为是否正确?

在此先感谢 L

4

1 回答 1

0

是的,这是flatten的记录行为:它丢弃解析器的结果,并返回正在读取的输入中消耗范围的子字符串。

从问题中不清楚您的期望是什么?

  • 您可能想要使用令牌解析器:sentence.token().parse('three apples'). 这将产生一个Token包含两者的对象,通过 Token.value 解析的列表和通过[3, 'apples']Token.input消耗的输入字符串。'three apples'
  • 或者,您可能希望使用自定义映射函数转换解析列表:sentence.map((list) => '${list[0]} ${list[1]}')yield '3 apples'
于 2020-10-28T18:14:03.593 回答