用于模式匹配的数组中的Scala占位符

时间:2017-05-26 07:23:59

标签: arrays scala pattern-matching

我想匹配第一个元素为0或1或Null的数组,下面是示例:

def getTheta(tree: Node, coding: Array[Int]): Array[Double] = {
    val theta = coding.take(coding.length - 1) match {
        case Array() => tree.theta
        case Array(0,_) => getTheta(tree.right.asInstanceOf[Node],coding.tail)
        case Array(1,_) => getTheta(tree.left.asInstanceOf[Node],coding.tail)
    }
    theta
}

树类定义是:

sealed trait Tree

case class Leaf(label: String, popularity: Double) extends Tree

case class Node(var theta: Array[Double], popularity: Double, left: Tree, right: Tree) extends Tree

实际上我知道Array(0,__)或Array(1,_)是错误的,但我关心的只是数组的第一个元素,我该如何匹配呢?

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

你可以在Array中使用varags来实现这一点。

coding.take(coding.length - 1) match {
   case Array(0, _ *)  => getTheta(tree.left.asInstanceOf[Node],coding.tail)
   case Array(1, _ *)  => getTheta(tree.right.asInstanceOf[Node],coding.tail)
   case Array() =>  getTheta(tree.right.asInstanceOf[Node],coding.tail)
}

其他选项

  • 将数组转换为列表

    coding.take(coding.length - 1).toList match {
      case 1 :: tail => getTheta(tree.right.asInstanceOf[Node],coding.tail)
      case 0 :: tail => getTheta(tree.left.asInstanceOf[Node],coding.tail)
      case Nil =>  getTheta(tree.left.asInstanceOf[Node],coding.tail)
    }
    
  • 如果模式中的警卫匹配如下,则使用

    coding.take(coding.length - 1) match {
        case x if x.head == 0 => getTheta(tree.right.asInstanceOf[Node],coding.tail)
        case x if x.head == 1 => getTheta(tree.left.asInstanceOf[Node],coding.tail)
        case Array() =>  getTheta(tree.left.asInstanceOf[Node],coding.tail)
    }