平衡功能我已經寫了一個函數來平衡括號,但我已經遇到了一些問題括號中階
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}
後執行?
因爲你的第一個'if'只是被吞噬 - 'if(..)else ..; if(..)else ...' - 當你編寫這樣的代碼時,兩個if都被執行,但是第一個結果被忽略,代碼流轉到下一個if語句(不管列表是否爲空或者不是 - 正如我所說,首先檢查被忽略)。 –