【发布时间】: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