[英]Scala - string of algebraic operations
我有一个表示一些基本代数运算的字符串,例如:
"42 * 67 + 4"
我想要一个类型的函数
function (operation: String) : Int = {}
这样它需要一串代数运算并返回实际的最终值,在这种情况下:2818
我会知道如何从这样的字符串中提取数字,但是我还不清楚如何提取诸如“ +”,“-”,“ *”,“ /”之类的数学运算并实际进行计算。
在没有任何外部库的情况下,实现Shunting-yard算法来进行这种计算非常简单:
def calculate(operation: String): Int = {
var results: List[Int] = Nil
var operators: List[String] = Nil
def precedence(operator: String) = operator match {
case "+" | "-" => 0
case "*" | "/" => 1
}
def execute(operator: String): Unit = {
(results, operator) match {
case (x :: y :: rest, "+") => results = (y + x) :: rest
case (x :: y :: rest, "-") => results = (y - x) :: rest
case (x :: y :: rest, "*") => results = (y * x) :: rest
case (x :: y :: rest, "/") => results = (y / x) :: rest
case (_, _) => throw new RuntimeException("Not enough arguments")
}
}
for (term <- "[1-9][0-9]*|[-+/*]".r.findAllIn(operation)) {
util.Try(term.toInt) match {
case util.Success(number) => results ::= number
case _ =>
val (operatorsToExecute, rest) =
operators.span(op => precedence(op) >= precedence(term))
operatorsToExecute foreach execute
operators = term :: rest
}
}
operators foreach execute
results match {
case res :: Nil => res
case _ => throw new RuntimeException("Too many arguments")
}
}
这使用整数除法:
scala> calculate("3 / 2")
res0: Int = 1
并具有正确的加法和乘法优先级:
scala> calculate("2 + 2 * 2")
res1: Int = 6
支持:
2 * (2 + 2)
, Try[Int]
, Option[Int]
等,而不是返回裸Int
或抛出错误的当前行为) 留给读者练习。
对于更复杂的事情,当然最好使用scala-parser-combinators
或其他答案中建议的某些第三方解析库。
因此,@GáborBakos发布了他的笑话评论,而我仍在撰写和测试我的笑话答案,但无论如何我都会将其发布。
注意:有效。 有时。 一点点。 注意2:这是个玩笑!
def function(operation: String) = {
val js = new javax.script.ScriptEngineManager().getEngineByName("JavaScript")
js.eval(operation) match { case i: Integer => i.asInstanceOf[Int] }
}
function("42 * 67 + 4")
// => 2818 : Int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.