在尝试编写一个简单的括号平衡函数时,我了解到我不知道 scala 如何评估 if 语句。
def balance(chars: List[Char]): Boolean = {
def loop(chars: List[Char], opened: Int): Boolean = {
println(opened)
println(chars.head)
if (opened < 0) return false
if (chars.isEmpty && opened == 0) return true
if (chars.isEmpty && opened > 0) return false
if (!chars.isEmpty && chars.head.toString == "(") loop(chars.tail, opened+1)
if (!chars.isEmpty && chars.head.toString == ")") loop(chars.tail, opened-1)
else loop(chars.tail, opened)
}
loop(chars, 0)
}
当我运行它时,到第三次迭代时,它将 println(opened) 并声明打开 = -1。我以为 (opened < 0) ----> (-1 < 0) -----> true,所以我会返回 false。事实并非如此——为什么?