评估列表作为数学表达式
我有一个充满值和运算符的 List
。
["123", "+", "(", "890", "-", "15.00", ")"]
我知道我可以制定一种算法,将这些数字和运算符压入堆栈,然后将它们弹出并进行评估。但是,有没有更好的方法来不使用外部库呢?
I have a List<String>
that is full of values and operators.
["123", "+", "(", "890", "-", "15.00", ")"]
I know that I can make an algorithm that will push these numbers and and operators onto a stack and pop them off and evaluate as I go. But, is there a better way to do with without using a external library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将数字和运算符压入堆栈将是一个解释器。
明显更好的方法(对于“更好”的某些定义)是编写一个编译器!
您已经将输入拆分为词法标记,因此您可以跳过实现词法分析器并可以直接深入构建 AST。您可以在系统中找到合适的类来将输入转换为目标。林克。表达式命名空间;查看表达式类。您可以将结果包装在 lambda 表达式中,将其编译为 IL 并在 CLR 上执行!
Pushing the numbers and operators onto a stack would be an interpreter.
The obvious better way to do this (for some definition of "better") is to write a compiler!
You already have the input split into lexical tokens, so you can skip implementing a lexer and can dive right into building the AST. You can find suitable classes to transform your input to in the System.Linq.Expressions Namespace; have a look at the Expression Class. You can wrap the result in a lambda expression, compile it to IL and execute it on the CLR!
您可以加入
List
,然后让编译器在运行时对其进行评估,如 Mehrdad 所说。我发现此处已经提出了一个非常类似的问题
更新:
NCalc “NCalc - .NET 数学表达式求值器”,即使这是一个外部库我认为它是一个开源项目,这意味着您可以将代码直接添加到您的项目中。
更新:
您可以使用 String.Join 函数加入列表。
You can join the
List
and then let the compiler evaluate it at runtime as Mehrdad stated.I found a very similar question already asked here
update :
NCalc "NCalc - Mathematical Expressions Evaluator for .NET" even though this is an external library I think it is an open source project which means you can add the code directly to your project.
Update :
You can use the
String.Join
function to join the List.您始终可以使用 .NET 框架中的 C# 编译器类将其计算为 C# 表达式...
You can always use the C# compiler classes in the .NET framework to evaluate it as a C# expression...
我有一个完整的类可以计算任何表达式。
首先,您需要将列表中的所有字符串提取为单个字符串,例如:
其次,您需要在解析器中计算此表达式,我有一个完整的类可以为您完成此操作,但我无法在此处附加文件。
I have a complete class that calculates any expression.
First, you need to extract all strings of your list to a single string, like:
Second, you need to evaluate this expression in a parser, I have a complete class that makes this for you, but I can't attach files here.