【问题标题】:Why is my functionality changing by moving some logic?为什么我的功能会通过移动一些逻辑来改变?
【发布时间】:2017-01-13 02:25:36
【问题描述】:

即使使用assert(!balance("())(".toList)),它的行为也符合预期:

def balance(chars: List[Char]): Boolean = {
  def balanceR(chars: List[Char], depth: Int): Boolean = {
    if (chars.isEmpty)
      depth == 0

    else if (chars.head == '(') balanceR(chars.tail, depth + 1)
    else if (chars.head == ')') {
      if (depth == 0) false else balanceR(chars.tail, depth - 1)
    }
    else balanceR(chars.tail, depth)
  }
  balanceR(chars, 0)
}

但是,将逻辑的位置修改为“如果深度变为负数则返回 false”会导致相同的断言失败:

def balance(chars: List[Char]): Boolean = {
  def balanceR(chars: List[Char], depth: Int): Boolean = {
    if (depth < 0)
      false

    if (chars.isEmpty)
      depth == 0

    else if (chars.head == '(') balanceR(chars.tail, depth + 1)
    else if (chars.head == ')') balanceR(chars.tail, depth - 1)
    else balanceR(chars.tail, depth)
  }
  balanceR(chars, 0)
}

chars.head")"时的递归调用应该为balanceR("(", -1)时,为什么第二个函数不为"())("返回false?

请注意,这是来自 Scala Coursera,请在此处查看有关该主题的 mod 评论:Scala way to program bunch of if's

【问题讨论】:

    标签: scala


    【解决方案1】:

    您已经创建了一个实际上什么都不做的独立表达式。

    if (depth < 0)
      false
    

    这将被评估为AnyVal(因为没有 else 分支),然后被丢弃。 balanceR 不返回这里。您可能打算将第二个 if 分支设为 else if

    【讨论】:

    • 嗯,这似乎是我误解 Scala 是如何返回的某种方式。我认为当它在 if 语句之后看到单个语句时,它会返回该语句。就像我不必说的那样:return balanceR(chars.tail, depth + 1)
    • 您的建议确实解决了问题。等效地,我可以在if 之后说return false(我认为这是隐含的),或者按照您的建议将第二个分支更改为else if,对吗?
    • @TaylorKline Scala 返回方法中最后一条语句的结果。任何不在方法末尾的语句(如您的第一个 if)都将被丢弃。就像你说的,你可以在这里使用 return,但通常最好避免使用 return。
    猜你喜欢
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2018-06-05
    相关资源
    最近更新 更多