案例类-组合模式匹配

时间:2019-07-01 17:10:44

标签: scala pattern-matching

我有一个定义如下的方法,想要组合模式匹配。 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

如何申请或规定条件?

1 个答案:

答案 0 :(得分:2)

您尝试的方法有几个问题:

  1. 您正在使用||Or运算符)而不是|Pipe运算符)来表示多种情况,如@Luis所评论-参见{{3 }}
  2. 在合并多个大小写时,您将尝试引用变量-请参见this question

所以您可以尝试的确实是:

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)
  }