1
我努力学习Scala和正在做的任务,但我无法找出以下的结果......差异,因为报价
所以,问题是递归弄清楚括号是否平衡或不...递归。 所以这是我工作的解决方案..
def balance(chars: List[Char]): Boolean = {
def iterate(chars: List[Char], sum:Int):Int = {
if(chars.isEmpty || sum<0) sum
else if(chars.head == '(') iterate(chars.tail ,sum+1)
else if(chars.head == ')') iterate(chars.tail,sum-1)
else iterate(chars.tail, sum)
}
iterate(chars,0) == 0
}
但是,如果我的代码更改为以下
def balance(chars: List[Char]): Boolean = {
def iterate(chars: List[Char], sum:Int):Int = {
if(chars.isEmpty || sum<0) sum
else if(chars.head == "(") iterate(chars.tail ,sum+1) //NOTE double quotes
else if(chars.head == ")") iterate(chars.tail,sum-1) //NOTE double quotes
else iterate(chars.tail, sum)
}
iterate(chars,0) == 0
}
这总是返回true ...
为什么?
//test with
val s1 = ":-)"
println(balance(s1.toList))
如果p注意编译器的警告,你可能能够避免这样的问题。当我从上面的代码编译代码片段时,编译器告诉我'警告:使用'=='比较类型Char和String的值总是会产生false',并且它也给出了行号。 – DaoWen