I have to write a function to find if the parenthesises are balanced in a string. The problem is that in line 1, the if condition is always skipped.
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)
}
Even the IntelliJ idea shows it in a faded text(meaning that it is never evaluated).
CodePudding user response:
The faded code is evaluated, it is just ignored because the if
does nothing with it. You need to move the rest of the code into the else
part of the first if
and remove the spurious recursive call at the end:
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)
}
A cleaner way to do with is to use match
to test and extract head/tail at the same time:
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)
}
I've also changed the input type to String
as that seems more natural.