这个问题主要是关于语法问题
我有一个程序来计算括号的数量以确定它们是否匹配,因此必须有相同数量的"("和")",没有& #34;)"在"之前("
def balance(chars: List[Char]): Boolean = {
if (chars.isEmpty) throw new NoSuchElementException
def helper(chars: List[Char], num: Int = 0, check: Int = 1): (Int, Int) = {
if (num < 0) check = 0
if (chars.head == "(") return helper(chars.tail, num + 1)
if (chars.head == ")") return helper(chars.tail, num - 1)
else return(chars.tail, num)
}
if (num == 0 && check == 1) return true
else return false
}
这就是我想要做的事情:
根据列表定义一个返回Boolean
为true的函数
如果列表为空,则返回没有任何内容
定义一个辅助函数,它返回两个整数check和num
,可用作条件来确定括号是否匹配
如果num
小于零,则表示在左边有一个右括号,这是不可接受的,检查已更改为0
如果头部的字符值是左括号,我调用辅助函数,num
值增加一个
如果头部的字符值是右括号,我调用辅助函数,num
值减1;
如果头部中的字符值既不是右括号也不是左括号,我调用辅助函数时num
值减1;
此函数的要点是返回num
并检查变量以返回嵌套在
在外部函数中,我想确定在左侧(check == 0
)之前是否有右括号,或者它们不匹配(num != 1
)
我应该进行哪些语法更改?我喜欢这种逻辑思考事物的方式,所以请不要试图改变我的逻辑,除非我没有采用功能性的风格,并且仍然在考虑更多的程序性。
答案 0 :(得分:0)
我做了一些小改动以使您的代码正常工作:
def balance(chars: List[Char]): Boolean = {
if (chars.isEmpty) throw new NoSuchElementException
@scala.annotation.tailrec
def helper(chars: List[Char], num: Int = 0): Boolean = chars match {
case _ if num < 0 => false
case head :: tail if head == '(' =>
helper(tail, num + 1)
case head :: tail if head == ')' =>
helper(tail, num - 1)
case head :: tail =>
helper(tail, num)
case Nil => num == 0
}
helper(chars)
}
balance("()()()()(".toList) //res0: Boolean = false
balance("(adsads)()()()sdfsdfsdf".toList) //res1: Boolean = true
balance("(()()()(asdasd))".toList) //res2: Boolean = true
balance("asdasd".toList) //res3: Boolean = true
balance("()()(()(".toList) //res4: Boolean = false
balance("".toList) // java.util.NoSuchElementException
或没有模式匹配:
def balance(chars: List[Char]): Boolean = {
if (chars.isEmpty) throw new NoSuchElementException
@scala.annotation.tailrec
def helper(chars: List[Char], num: Int = 0): Boolean = {
if (num < 0)
false
else if(chars.isEmpty)
num == 0
else if(chars.head == '(')
helper(chars.tail, num + 1)
else if(chars.head == ')')
helper(chars.tail, num - 1)
else
helper(chars.tail, num)
}
helper(chars)
}
balance("()()()()(".toList) //res0: Boolean = false
balance("(adsads)()()()sdfsdfsdf".toList) //res1: Boolean = true
balance("(()()()(asdasd))".toList) //res2: Boolean = true
balance("asdasd".toList) //res3: Boolean = true
balance("()()(()(".toList) //res4: Boolean = false
balance("".toList) // java.util.NoSuchElementException