语法菜鸟在这里。
我需要解析类似于 SymPy 接受的数学公式,并将它们转换为某种从左到右的语法树,使用 Nearley这个语法。
当我有一个表达式,比如a*sin(x)*y
wheresin
首先被识别为 a SY
,然后是 a时,就会出现问题FN
。如果我想能够解析变量(这就是SY
目的),我认为这是一种必要的邪恶。结果是这样的
[ { type: 'Symbol',
properties: { letter: 'a' },
children:
{ right:
{ type: 'Symbol',
properties: { letter: 'sin' },
children:
{ right:
{ type: 'Fn',
properties: { name: 'sin' },
children:
{ argument: { type: 'Symbol', properties: { letter: 'x' }, children: {} },
right: { type: 'Symbol', properties: { letter: 'y' }, children: {} } } } } } },
position: { x: 200, y: 200 } } ]
更糟糕的是,当表达式为 时a*sin(x)^y
,我得到
[ { type: 'Symbol',
properties: { letter: 'a' },
children:
{ right:
{ type: 'Symbol',
properties: { letter: 'sin' },
children:
{ right:
{ type: 'Fn',
properties: { name: 'sin' },
children:
{ argument: { type: 'Symbol', properties: { letter: 'x' }, children: {} },
superscript: { type: 'Symbol', properties: { letter: 'y' }, children: {} },
right: [Circular] } } } } },
position: { x: 200, y: 200 } } ]
我想这[Circular]
意味着某处存在某种邪恶的循环。
我怀疑我可以解决上面硬编码检查的第一个问题,如果两个“匹配”,则SY
用正确FN
的替换检查,但我宁愿避免这样的混乱。我不知道第二个发生了什么——尽管我已经为此做了一整天,而且我的头脑很可能是阴云密布。我今天一到办公室再调查一下。
有什么线索吗?
编辑:我设法用一个可怕的黑客“解决”了第一个问题(Fn
作为一个Symbol
同名的孩子)。循环问题依然存在。我正在调查,但我可能会发现另一个可怕的黑客。如果可能的话,我宁愿看到语法的修复而不是转换函数。