Scala way to program bunch of if's

后端 未结 4 1358
北恋
北恋 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 09:05

    var parens :List[Char] =  Nil
    def matcher(chrs: List[Char]): Boolean = {
         if (chrs.isEmpty) {
            return parens.isEmpty
         }
         else {
             chrs.head match {
               case '(' =>  parens = '(' :: parens ;matcher(chrs.tail)
               case ')' =>  if (parens.isEmpty) return false 
                                else if (parens.apply(0) ==  '(') parens = parens.drop(1) 
                                else return false;  
                                matcher(chrs.tail);
               case _ => matcher(chrs.tail)
             }
         }
    }
    

    As you can see I didn't use count because count won't work on ())(

提交回复
热议问题