如何使用递归在Scala中进行反向抛光符号?

时间:2019-03-29 00:10:23

标签: algorithm scala tree

我试图在Scala中制作RPN,但在控制台中出现异常

  

线程“ main” scala.MatchError中的异常:1(类   java.lang.Character)

我停在这里,因为Intelij没有显示问题所在。我认为我做错了

if (!expr.isEmpty) {
  expr.head match 

但是我花了一些时间思考如何进行交换,但我没有发明任何东西

我用Java编写了此程序,但在函数式编程中,我不知道如何正确地将此匹配与尾部递归


object RPN extends App {

  print(evaluate("123++"))
 def evaluate( expr : String)  {
   val stack =  Stack[Double]()

   var  a,b  :Int=0
   @tailrec
def helper ( asset : String){

if (!expr.isEmpty) {
  expr.head match {
    case it if 0 until 9 contains it => stack.push(expr.head); helper(asset.tail)
    case '+' => b = stack.pop.toString().toInt; a = stack.pop.toString().toInt; stack.push(a + b)
    case '-' => b = stack.pop.toString().toInt; a = stack.pop.toString().toInt; stack.push(a - b)
    case '*' => b = stack.pop.toString().toInt; a = stack.pop.toString().toInt; stack.push(a * b)
    case '/' => b = stack.pop.toString().toInt; a = stack.pop.toString().toInt; stack.push(a / b)
  }
}
else return stack.pop
    }
   helper(expr)

}
}

1 个答案:

答案 0 :(得分:2)

您的代码正在expr内引用helper(),而您可能想在其中引用asset

此外,您不需要returnvar

def evaluate(expr :String) :Double = {
  val stack = collection.mutable.Stack[Double]()

  @annotation.tailrec
  def helper(asset :String) :Double =
    if (asset.isEmpty) stack.pop
    else {
      asset.head match {
        case c if c.isDigit => 
                    stack.push(c.asDigit)
        case '+' => stack.push(stack.pop + stack.pop)
        case '-' => stack.push(-stack.pop + stack.pop)
        case '*' => stack.push(stack.pop * stack.pop)
        case '/' => stack.push(1/stack.pop * stack.pop)
        case  c  => throw new Error(s"Bad Char: $c")
      }
      helper(asset.tail)
    }

  helper(expr)
}

测试:

evaluate("123++")  //res0: Double = 6.0
evaluate("954--")  //res1: Double = 8.0
evaluate("423*+")  //res2: Double = 10.0
evaluate("28/")    //res3: Double = 0.25
evaluate("73/")    //res4: Double = 2.333333333333333