Scala way to program bunch of if's

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

    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
    

提交回复
热议问题