This one behaves as intended, even with 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)
}
However, modifying the placement of the logic to "return false if depth becomes negative" causes the same assertion to fail:
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)
}
Why does the second function not return false for "())("
, when the recursive call when the chars.head
is ")"
should be balanceR("(", -1)
?
Note that this is from the Scala Coursera, and see the mod comment here on that topic: Scala way to program bunch of if's