Scala 编程一堆 if 的方法 [英] Scala way to program bunch of if's

查看:18
本文介绍了Scala 编程一堆 if 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 scala 开始,并尝试将函数式方法应用于它,但我得出了一堆难以阅读的嵌套 ifelse 结构,我想知道有没有更好的方法来编程这些东西?

I'm starting out with scala, and trying to apply the functional way to it, but I came out with bunch of nested ifelse 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())
  }

我怎样才能写得更实用、更像 Scala?

How can I write it to be more functional and more scala like?

推荐答案

把它写成折叠可能更好:

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

这篇关于Scala 编程一堆 if 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆