为什么展平摆脱映射值?
Why flatten gets rid of mapped values?
我正在尝试解析一个句子,同时将数字转换为其数字表示形式。
作为一个简单的例子,我想要句子
three apples
解析并转换为
3 apples
使用这段简单的代码,我实际上可以正确地解析句子并将 three 转换为 3,但是当我尝试将结果,3 恢复为 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'));
我错过了什么吗? flatten 行为是否正确?
提前致谢
大号
是的,这是 flatten 的记录行为:它丢弃解析器的结果,returns sub-string正在读取输入。
从问题中看不清楚你期望的是什么?
- 您可能想要使用 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。
- 或者,您可能希望使用自定义 mapping function 转换解析列表:
sentence.map((list) => '${list[0]} ${list[1]}')
产生 '3 apples'
.
我正在尝试解析一个句子,同时将数字转换为其数字表示形式。
作为一个简单的例子,我想要句子
three apples
解析并转换为
3 apples
使用这段简单的代码,我实际上可以正确地解析句子并将 three 转换为 3,但是当我尝试将结果,3 恢复为 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'));
我错过了什么吗? flatten 行为是否正确?
提前致谢 大号
是的,这是 flatten 的记录行为:它丢弃解析器的结果,returns sub-string正在读取输入。
从问题中看不清楚你期望的是什么?
- 您可能想要使用 token parser:
sentence.token().parse('three apples')
. This will yield aToken
object that contains both, the parsed list[3, 'apples']
through Token.value and the consumed input string'three apples'
through Token.input。 - 或者,您可能希望使用自定义 mapping function 转换解析列表:
sentence.map((list) => '${list[0]} ${list[1]}')
产生'3 apples'
.