我有一个定义如下的方法,想要组合模式匹配。 or运算符给我编译器错误(||)。
def isPaired(input: String): Boolean = {
def go(x: List[Char], level: Int = 0): Boolean = {
x match {
case Nil => true
case '(' :: xs1 if level < 0 => false
case '[' :: xs1 if level < 0 => false
case '{' :: xs1 if level < 0 => false
case ')' :: xs1 if level == 0 => false
case ']' :: xs1 if level == 0 => false
case '}' :: xs1 if level == 0 => false
case '(' :: xs1 => go(xs1, level + 1)
case '[' :: xs1 => go(xs1, level + 1)
case '{' :: xs1 => go(xs1, level + 1)
case ')' :: xs1 => go(xs1, level - 1)
case ']' :: xs1 => go(xs1, level - 1)
case '}' :: xs1 => go(xs1, level - 1)
case _ :: xs1 => go(xs1, level + 1)
}
}
go(input.toList)
}
下面给出了编译器错误:
case '(' :: xs1 || '[' :: xs1 || '{' :: xs1 if level < 0 => false
case ('(' :: xs1) || ('[' :: xs1) || ('{' :: xs1) if level < 0 => false
如何申请或规定条件?
答案 0 :(得分:2)
您尝试的方法有几个问题:
||
(Or
运算符)而不是|
(Pipe
运算符)来表示多种情况,如@Luis所评论-参见{{3 }} 所以您可以尝试的确实是:
def isPaired(input: String): Boolean = {
def go(x: List[Char], level: Int = 0): Boolean = {
x match {
case Nil => true
case ('(' | '[' | '{') :: xs1 if level < 0 => false
case ')' :: xs1 if level == 0 => false
case ']' :: xs1 if level == 0 => false
case '}' :: xs1 if level == 0 => false
case '(' :: xs1 => go(xs1, level + 1)
case '[' :: xs1 => go(xs1, level + 1)
case '{' :: xs1 => go(xs1, level + 1)
case ')' :: xs1 => go(xs1, level - 1)
case ']' :: xs1 => go(xs1, level - 1)
case '}' :: xs1 => go(xs1, level - 1)
case _ :: xs1 => go(xs1, level + 1)
}
}
go(input.toList)
}
或更简洁:
def isPaired(input: String): Boolean = {
def go(x: List[Char], level: Int = 0): Boolean = {
x match {
case Nil => true
case ('(' | '[' | '{') :: xs1 if level < 0 => false
case (')' | ']' | '}') :: xs1 if level == 0 => false
case ('(' | '[' | '{') :: xs1 => go(xs1, level + 1)
case (')' | ']' | '}') :: xs1 => go(xs1, level - 1)
case _ :: xs1 => go(xs1, level + 1)
}
}
go(input.toList)
}