【问题标题】:Scala "balance the scopes" recursion [duplicate]Scala“平衡范围”递归[重复]
【发布时间】:2018-01-02 18:48:44
【问题描述】:

我编写代码,检查字符串中的括号余额:

def balance(chars: List[Char]): Boolean = {

      def scopes(chars: List[Char], s: Int): Boolean = {
        if (chars.isEmpty)
          if (s == 0) true
          else false
        else{
          if (s < 0) return false
          if (chars.head.toString == "(") scopes(chars.tail, s + 1)
          if (chars.head.toString == ")") scopes(chars.tail, s - 1)


          else scopes(chars.tail, s)
        }
      }
      scopes(chars, 0)
    }
balance("if zero? x( max / 1 x".toList)

但它工作错了。我只是找不到错误。需要帮助,请

【问题讨论】:

    标签: scala recursion


    【解决方案1】:

    您在嵌套的if ... 块中缺少else:对scopes 的第一次递归调用无效,因为它总是被scopes(chars.tail, s) 覆盖...

    一般来说,if..else 块,尤其是嵌套块,通常最好写成match 子句,这样更易​​读,更不容易出错。此外,return 语句很糟糕,应该(几乎)永远不要在 scala 中使用。

     @tailrec
     def scopes(chars: List[Char], s: Int = 0): Boolean = chars match {
       case Nil => s == 0
       case _ if s < 0 => false
       case "(" :: tail => scopes(tail, s+1)
       case ")" :: tail => scopes(tail, s-1)
       case _ :: tail => scopes(tail, s)
     }
    

    另外,我建议在您希望算法是尾递归的任何地方使用@tailrec 标签。例如,在您的情况下,使用该标记会在编译时捕获错误 - 对 scopes 的第一次递归调用不在尾部位置,尽管它应该是。

    【讨论】:

    • 哈哈,我太不耐烦了——谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2012-09-10
    相关资源
    最近更新 更多