2012-09-28 19 views
2

我想學習斯卡拉,我是一個新手。我知道這不是最佳的功能代碼,並歡迎任何人都可以給我的建議,但我想明白爲什麼我一直對此功能感到滿意。斯卡拉總是迴歸真實....爲什麼?

def balance(chars: List[Char]): Boolean = { 
    val newList = chars.filter(x => x.equals('(') || x.equals(')')); 
    return countParams(newList, 0) 
    }            

    def countParams(xs: List[Char], y: Int): Boolean = { 
    println(y + " right Here") 
    if (y < 0) { 
     println(y + " Here") 
     return false 
    } else { 
     println(y + " Greater than 0") 
     if (xs.size > 0) { 
     println(xs.size + " this is the size") 
     xs match { 
      case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1) 
      case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1) 
      case xs => 0 
     } 
     } 
    } 
    return true; 
    } 
    balance("()())))".toList) 

我知道,我打我的if語句的假分支,但它仍然在我的函數結束時返回true。請幫助我理解。謝謝。

+2

因爲你在方法的末尾寫了true。 – phant0m

+0

我也在使用#progfun,並且我認爲我的家庭作業解決方案中沒有多少代碼行。 –

回答

3

您要麼必須更明確地表明您要返回的內容,要麼使其對編譯器更加明確。這工作:

def countParams(xs: List[Char], y: Int): Boolean = { 
    println(y + " right Here") 
    if (y < 0) { 
     println(y + " Here") 
     false 
    } else { 
     println(y + " Greater than 0") 
     if (xs.size > 0) { 
     println(xs.size + " this is the size") 
     xs match { 
      case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1) 
      case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1) 
      case xs => false 
     } 
     } else { 
     true 
     } 
    } 
} 

if每個分支上面的代碼,所以編譯器假定它是要返回的值返回一定的價值。順便說一句沒有日誌記錄和更多的慣用語:

def countParams(xs: List[Char], y: Int) = 
    xs match { 
     case Nil => y == 0 
     case '(' :: rest => countParams(rest, y + 1) 
     case ')' :: rest if(y > 0) => countParams(rest, y - 1) 
     case _ => false //must be closing parens but y < 0 
    } 
2

scala中的if是一個表達式。它返回一個值,如果在其他語言中,它在概念上與三元相似。

如果你想在你的else分支中返回一些東西,你應該有一個嵌套的if和else來允許它返回一個值。

換句話說,countParams正在評估所有代碼並落在正在分配給countParams的塊({})中的最後一行。那就是,true;

簡而言之,在countParams的末尾丟失true,並給出您的嵌套,如果其他返回有意義的東西。