Scala way to program bunch of if's

后端 未结 4 1356
北恋
北恋 2020-12-08 08:03

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

4条回答
  •  自闭症患者
    2020-12-08 08:43

    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)
    }
    

提交回复
热议问题