36 lines
973 B
Scala

import scala.annotation.tailrec
def balanceMatch(chars: List[Char]): Boolean = {
@tailrec
def checkStep(chars: List[Char], n: Int): Boolean = {
if (chars.isEmpty) n == 0
else if (n < 0) false
else checkStep(chars.tail, chars.head match {
case '(' => n + 1
case ')' => n - 1
case _ => n
})
}
checkStep(chars, 0)
}
def balanceMatch2(chars: List[Char]): Boolean = {
@tailrec
def checkStep(chars: List[Char], n: Int): Boolean = {
chars match {
case Nil => n == 0
case _ if n < 0 => false
case '('::rest => checkStep(rest, n + 1)
case ')'::rest => checkStep(rest, n - 1)
case _::rest => checkStep(rest, n)
}
}
checkStep(chars, 0)
}
balanceMatch2("(if (x == 0) then max (1, x))".toList)
balanceMatch2("I told him (that it's not (yet) done). (But he wasn't listening)".toList)
balanceMatch2(")".toList)
balanceMatch2("())()".toList)
balanceMatch2("())(()".toList)
balanceMatch2("(".toList)