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
Adding to Vigneshwaran's answer (including comments & filtering unnecessary letters to avoid extra recursive calls):
def balance(chars: List[Char]): Boolean = {
@scala.annotation.tailrec
def recurs_balance(chars: List[Char], openings: Int): Boolean = {
if (chars.isEmpty) openings == 0
else if (chars.head == '(') recurs_balance(chars.tail, openings + 1)
else openings > 0 && recurs_balance(chars.tail, openings - 1)
}
recurs_balance(chars.filter(x => x == '(' || x == ')'), 0)
}