2017-05-26 32 views
0

我想匹配一个数组,其第一个元素是0或1或Null,下面是例如:Scala的占位符阵列,用于图案匹配

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,_)是错误的,但我关心的只是Array的第一个元素,我该如何匹配它?

有人可以帮助我吗?

+0

避免使用asInstanceOf不安全 – Pavel

+0

谢谢! @ Cyeegha,之前我没有看到这个问题,实际上我的问题也是一样的。 – Yang

+0

通常你应该返回Option [Node],然后使用模式匹配来查看结果是什么 – Pavel

回答

1

您可以使用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) 
    } 
    
+1

感谢亿,转换成List是一个很好的选择。 – Yang