I\'m starting out with scala, and trying to apply the functional way to it, but I came out with bunch of nested if\\else constructions which is hard to read, and I wonder is
I don't think there is any reason to filter the list before you traverse it. You can just ignore the non parentheses as you traverse the list. I think it is also unnecessary to build the second list. All you really want to know is that the count of open parenthesis is never negative:
def balance(chars: List[Char]): Boolean = {
@tailrec
def _balance(chars: List[Char], count: Int) : Boolean =
chars match {
case Nil => count == 0 // end of the string did we close every open?
case '(' :: xs => _balance(xs, count+1)
case ')' :: xs => (count > 0) && _balance(xs, count-1)
case _ => _balance(chars.tail, count) // uninteresting char, skip it
}
_balance(chars, 0)
}