2013-06-19 51 views
0

平衡功能我已經寫了一個函數來平衡括號,但我已經遇到了一些問題括號中階

def subfunc(left: Int, chars: List[Char]): Boolean = { 
    if (chars.isEmpty) { 
    if (left == 0) { println("true"); true } 
    else false 
    **} else {** 
    if (chars.head == '(') subfunc(left + 1, chars.tail) 
    else if (chars.head == ')') { 
     if (left > 0) subfunc(left - 1, chars.tail) 
     else false 
    } else 
     subfunc(left, chars.tail) 
    } 
} 

當FUNC是這樣的,perfermance是好的,但如果我的RM }其他{ 而成爲本

def subfunc(left: Int, chars: List[Char]): Boolean = { 
    if (chars.isEmpty) { 
     if (left == 0) { println("true"); true } 
     else false 
    } 
    println("come to here") 
    if (chars.head == '(') subfunc(left + 1, chars.tail) 
    else if (chars.head == ')') { 
     if (left > 0) subfunc(left - 1, chars.tail) 
     else false 
    } else 
     subfunc(left, chars.tail) 
    } 

和測試碰撞

subfunc(0, chars)        //> come to here? 
                //| come to here? 
                //| come to here? 
                //| come to here? 
                //| come to here? 
                //| true 
                //| come to here? 
                //| java.util.NoSuchElementException: head of empty list 
                //| at scala.collection.immutable.Nil$.head(List.scala:337) 
                //| at scala.collection.immutable.Nil$.head(List.scala:334) 
                //| at recfun.expriment$$anonfun$main$1.subfunc$1(recfun.expriment.scala:22) 
                //| 
                //| at recfun.expriment$$anonfun$main$1.apply$mcV$sp(recfun.expriment.scala: 
                //| 35) 
                //| at org.scalaide.worksheet.runtime.library.WorksheetSupport$$anonfun$$exe 
                //| cute$1.apply$mcV$sp(WorksheetSupport.scala:76) 
                //| at org.scalaide.worksheet.runtime.library.WorksheetSupport$.redirected(W 
                //| orksheetSupport.scala:65) 
                //| at org.scalaide.worksheet.runtime.library.WorksheetSupport$.$execute(Wor 
                //| ksheetSupport.scala:75) 
                //| at recfun.expriment$.main(recfun.expriment.scala:3) 
                //| at recfun.expriment.main(recfun.expriment.scala) 
代碼

看來,該方案涉及到subfunc(0,的emptyList) 但爲什麼它打印「來這裏」行

if (left == 0) { println("true"); true} 

後執行?

+0

因爲你的第一個'if'只是被吞噬 - 'if(..)else ..; if(..)else ...' - 當你編寫這樣的代碼時,兩個if都被執行,但是第一個結果被忽略,代碼流轉到下一個if語句(不管列表是否爲空或者不是 - 正如我所說,首先檢查被忽略)。 –

回答

1

因爲scala只返回最後一個函數表達式
你的第一個代碼類似於返回任一分支的結果if(chars.isEmpty)。您的第二個代碼類似於,如果先執行,則返回chars.head == '('.的任一分支的結果。就是這樣 - 當你用這種方式編寫代碼時,函數在第一個if後並不急於返回

+0

順便謝謝你〜\ n – shuaizki

+0

,我想問你學習scala的方法。 – shuaizki