2013-10-20 37 views
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)) 
+1

如果p注意编译器的警告,你可能能够避免这样的问题。当我从上面的代码编译代码片段时,编译器告诉我'警告:使用'=='比较类型Char和String的值总是会产生false',并且它也给出了行号。 – DaoWen

回答

5

chars.head是一个字符, '(' 是一个字符,但 “(” 是一个字符串,那么这两个分支将始终evalate假

else if(chars.head == "(") iterate(chars.tail ,sum+1) //NOTE double quotes 
else if(chars.head == ")") iterate(chars.tail,sum-1) //NOTE double quotes 
1

使用的比赛,你” d见一个错误:

<console>:11: error: type mismatch; 
found : String("(") 
required: Char 
       case "(" => loop(cs.tail, sum + 1) 
        ^

与更正后的代码:

def balance(cs: Seq[Char]) = { 
    def loop(cs: Seq[Char], sum: Int): Int = { 
    if (cs.isEmpty || sum < 0) sum 
    else { 
     val i = cs.head match { 
     case '(' => 1 
     case ')' => -1 
     case _ => 0 
     } 
     loop(cs.tail, sum + i) 
    } 
    } 
    loop(cs, 0) == 0 
}