我必須撰寫一個函式來查找括號在字串中是否平衡。問題是在第 1 行中,if 條件總是被跳過。
def balance(chars: List[Char]): Boolean = {
def butil(chars: List[Char], l: Int, r: Int): Boolean ={
if (chars.isEmpty) l==r
val c = chars.head
val ret = c match {
case '(' => butil(chars.tail, l 1, r)
case ')' => if(l<=r) false else butil(chars.tail, l, r 1)
case _ => butil(chars.tail, l, r)
}
ret
}
butil(chars, 0, 0)
}
甚至 IntelliJ 的想法也以褪色的文本顯示它(這意味著它永遠不會被評估)。

uj5u.com熱心網友回復:
褪色的代碼被評估,它只是被忽略,因為它if不做任何事情。您需要將其余代碼移動到第else一個部分if并在最后洗掉虛假遞回呼叫:
def balance(chars: List[Char]): Boolean = {
def butil(chars: List[Char], l: Int, r: Int): Boolean = {
if (chars.isEmpty) {
l==r
} else {
println(chars.toString())
val c = chars.head
c match {
case '(' => butil(chars.tail, l 1, r)
case ')' => if(l<=r) false else butil(chars.tail, l, r 1)
case _ => butil(chars.tail, l, r)
}
}
}
butil(chars, 0, 0)
}
一種更簡潔的方法是同時使用match測驗和提取頭/尾:
def balance(chars: String): Boolean = {
def butil(chars: List[Char], l: Int, r: Int): Boolean =
chars match {
case Nil => l == r
case '(' :: tail => butil(tail, l 1, r)
case ')' :: tail => if (l <= r) false else butil(tail, l, r 1)
case _ :: tail => butil(tail, l, r)
}
butil(chars.toList, 0, 0)
}
我還將輸入型別更改String為看起來更自然。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/487569.html
上一篇:文本框文本只檢查一次
下一篇:如何減少if陳述句Python?
