Scala way to program bunch of if's

后端 未结 4 1357
北恋
北恋 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:46

    Well:

    1. You could start by writing it with else if conditions.
    2. Go ahead an annotate it with tailrec since it's tail-recursive.
    3. The filter condition can be written more simply as Set('(', ')'), which is a function from Char to Boolean
    4. I think you're missing the condition where 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())
    }
    

提交回复
热议问题