Return true if parentheses in list chars are balanced.

1
2
3
4
scala> balance("(foo (bar))".toList)
res1: Boolean = true
scala> balance("(foo bar".toList)
res2: Boolean = false

1
2
3
4
5
6
7
8
9
10
def balanceLeft(chars: List[Char], left: Int): Boolean = chars match {
  case Nil => left == 0
  case _ => chars.head match {
    case ')' => left > 0 && balanceLeft(chars.tail, left - 1)
    case '(' => balanceLeft(chars.tail, left + 1)
    case _ => balanceLeft(chars.tail, left)
  }
}

def balance(chars: List[Char]): Boolean = balanceLeft(chars, 0)