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 there nicer way to program such things?
For example I wrote a script, that performs parentheses balancing:
def balance(chars: List[Char]): Boolean = {
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 (parentesis.isEmpty)
false
else
checkParentesys(chars.tail, parentesis.tail)
checkParentesys(chars.filter(s => s == '(' || s == ')'), List())
}
How can I write it to be more functional and more scala like?
It might be nicer to write it as a fold:
def balance(chars: List[Char]): Boolean = chars.foldLeft(0){
case (0, ')') => return false
case (x, ')') => x - 1
case (x, '(') => x + 1
case (x, _ ) => x
} == 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With