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
Well:
else if
conditions. tailrec
since it's tail-recursive. Set('(', ')')
, which is a function from Char
to Boolean
chars
is empty but parenthesis
is not.So it would look like:
def balance(chars: List[Char]): Boolean = {
@tailrec
def checkParentesys(chars: List[Char], parentesis: List[Char]): Boolean =
if (chars.isEmpty && parentesis.isEmpty)
true
else if (chars.head == '(')
checkParentesys(chars.tail, '(' :: parentesis)
else if (chars.isEmpty || parentesis.isEmpty)
false
else
checkParentesys(chars.tail, parentesis.tail)
checkParentesys(chars.filter(Set('(', ')')), List())
}
You could also just turn the whole thing into a pattern match:
def balance(chars: List[Char]): Boolean = {
@tailrec
def checkParentesys(chars: List[Char], parentesis: List[Char]): Boolean =
(chars, parentesis) match {
case (Nil, Nil) => true
case ('(' :: charsTail, _) => checkParentesys(charsTail, '(' :: parentesis)
case (Nil, _) => false
case (_, Nil) => false
case (')' :: charsTail, '(' :: parentesisTail) => checkParentesys(charsTail, parentesisTail)
}
checkParentesys(chars.filter(Set('(', ')')), List())
}