最后,来自this question,问题仍然存在,这个subparser ......
private static void Factor(Scanner scanner, ref TermNode currentTree, ref Token currentToken)
{
Exponent(scanner, ref currentTree, ref currentToken);
while (currentToken is OperatorToken && ((OperatorToken)currentToken).OperatorChar == '^') // So long as the token is ^
{
TermNode node = new TermNode(currentTree, null, currentToken);
currentTree = null;
scanner.MoveNext();
currentToken = scanner.Current;
Exponent(scanner, ref currentTree, ref currentToken);
node.RightChild = currentTree;
currentTree = node;
}
}
...没有正确处理指数运算符(" ^")。这是因为它是正确的关联。上面的代码处理它就好像它是左关联的。
例如:文字e^x^2
被解释为(e^x)^2
。但是,正确的解释"将是e^(x^2)
。
我已经尝试过这样的事情:
if (/* The current token is ^ */)
{
TermNode node = new TermNode(tree, null, currentToken);
tree = null;
scanner.MoveNext();
currentToken = scanner.Current;
Exponent(ref tree);
node.RightChild = tree;
tree = node;
}
while (/* The current token is ^ */)
{
TermNode detachedExponent = tree.RightChild;
TermNode oldTree = tree;
Token token = currentToken;
tree.RightChild = null;
tree = null;
scanner.MoveNext();
currentToken = scanner.Current;
Exponent(ref tree);
oldTree.RightChild = new TermNode(distachedExponent, tree, token);
tree = oldTree;
}
仅适用于两个连续的" ^" - 表达式。不像e^x^y^z
那样(e^(x^(y^z))
而不是e^((x^y)^z)
就像解析器声称的那样...我错过了什么?
答案 0 :(得分:1)
如果您有a^b
,并且看到^c
,则会将其注入顶级^
的RHS,并创建a^(b^c)
,并留下结果充分表达。当您看到^d
后,再次将其注入顶级^
的RHS,创建a^((b^c)^d)
。您不应该将其注入顶级^
的RHS,而应注入右侧/最内侧^
表达式。要实现这一点,只需在单独的变量中跟踪该表达式即可。然后,不要修改顶级表达式RightChild
属性,而是修改子项。