斯卡拉方式来编程一堆if [英] Scala way to program bunch of if's

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

问题描述

我开始用scala,并尝试应用函数式的方式,但是我出来了一堆嵌套的if \\ else结构,很难阅读,我不知道有更好的方式来编程这样的事情?
例如,我编写了脚本,执行括号平衡

  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? 解决方案



  def balance(chars:List [Char]):Boolean = chars.foldLeft(0){
c ase(0,')')=> return false
case(x,')')=> x - 1
case(x,'(')=> x + 1
case(x,_)=> x
} == 0


i'am starting out with scala, and try to apply functional way to it, but i came out with bunch of nested if\else constructions wich is hard to read, and i wonder is there nicer way to program such things? For example i've wrote 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())
  }

Can you suggest, how i can write it 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

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

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