我写了一个平衡括号的函数,但是我遇到了一些问题
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 是这样的时候,性能还可以,但是如果我 rm } else { 并且代码变成了这个
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}
被执行?