I\'m working on some code to balance parenthesis, this question proved most useful for the algorithm.
I implemented it in my first language (PHP) but I\'m learning Scala
For what it's worth, here's a more idiomatic Scala implementation:
def balance(chars: List[Char]): Boolean = {
@tailrec def balanced(chars: List[Char], open: Int): Boolean =
chars match {
case Nil => open == 0
case '(' :: t => balanced(t, open + 1)
case ')' :: t => open > 0 && balanced(t, open - 1)
case _ :: t => balanced(t, open)
}
balanced(chars, 0)
}