0

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

Taylor Kline
  • 908
  • 3
  • 9
  • 30

1 Answers1

2

You've created a standalone expression that effectively does nothing.

if (depth < 0)
  false

This will be evaluated to AnyVal (since there's no else branch) and then discarded. balanceR does not return here. You probably meant for the second if branch to be an else if.

Ryan
  • 7,227
  • 5
  • 29
  • 40
  • Hmm, this seems to be some way that I am misunderstanding how Scala does returns. I thought that when it saw a single statement after an if-statement, it would return that statement. Like how I don't have to say: `return balanceR(chars.tail, depth + 1)` – Taylor Kline Jan 12 '17 at 18:28
  • Your suggestion does correct the problem. Equivalently I could say `return false` after the `if` (which I thought was implicit), or change the second branch to be an `else if` as you suggested, right? – Taylor Kline Jan 12 '17 at 18:31
  • 1
    @TaylorKline Scala returns the result of the last statement in the method. Any statement that isn't at the end of the method (like your first if) would simply be discarded. Like you say, you could use a return here, but it is usually better style to avoid using return. – puhlen Jan 12 '17 at 18:35