Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala way to program bunch of if's

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?

like image 653
Andrey Avatar asked Sep 21 '12 03:09

Andrey


1 Answers

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
like image 172
Luigi Plinge Avatar answered Oct 11 '22 22:10

Luigi Plinge