列出与其类型匹配的元素

时间:2011-06-09 08:39:28

标签: list scala pattern-matching

我有一个类似下面的代码:

def walkTree(list:List[Command]) {
    list match {
        case Command1::rest => doSomething(); walkTree(rest)
        case Command2::rest => doSomethingElse(); walkTree(rest)
        case Nil => ;
    }
}

我也知道您可以在特定类型上进行模式匹配并同时分配变量:

try {
    ...
}
catch {
    case ioExc:IOException => ioExc.printStackTrace()
    case exc:Exception => throw new RuntimeException("Oh Noes", e);
}

有没有办法将两者结合起来如下:

def walkTree(list:List[Command]) {
    list match {
        case cmd1:Command1::rest => doSomething(); walkTree(rest)
        case cmd2:Command2::rest => doSomethingElse(); walkTree(rest)
        case Nil => ;
    }
}

或者我需要在匹配之前提取每个列表元素吗?

2 个答案:

答案 0 :(得分:18)

是的,只需使用这样的括号(参见下面的示例):

def walkTree(list:List[Command]) {
    list match {
        case (cmd1:Command1)::rest => doSomething(); walkTree(rest)
        case (cmd2:Command2)::rest => doSomethingElse(); walkTree(rest)
        case Nil => ;
    }
}

但是,您不能使用foreach

scala> List(A(1), B(2), A(3), B(4), A(5)).foreach(_ match {
     |     case (a:A) => println("a:" + a)
     |     case (b:B) => println("b:" + b)
     | })
a:A(1)
b:B(2)
a:A(3)
b:B(4)
a:A(5)

示例:

scala> case class A(val i: Int);
defined class A

scala> case class B(val i: Int);
defined class B

scala> def walkTree(list: List[ScalaObject]) {
     |     list match {
     |         case (a:A)::rest => println("a:" + a); walkTree(rest);
     |         case (b:B)::rest => println("b:" + b); walkTree(rest);
     |         case Nil => ;
     |     }
     | }
walkTree: (list: List[ScalaObject])Unit

scala> walkTree(List(A(1), B(2), A(3), B(4), A(5)))
a:A(1)
b:B(2)
a:A(3)
b:B(4)
a:A(5)

答案 1 :(得分:4)

使用foreach然后对每个元素进行模式匹配似乎对我来说更清楚:

def walkTree(list:List[Command]) {
  list foreach {
    _ match {
      case cmd1:Command1 => doSomething()
      case cmd2:Command2 => doSomethingElse()
      case _ =>
    }
  }
}