斯卡拉方式来编程一堆if

编程入门 行业动态 更新时间:2024-10-14 06:20:38
本文介绍了斯卡拉方式来编程一堆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

本文发布于:2023-11-12 19:59:29,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斯卡   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!