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的第一個元素,我該如何匹配它?
有人可以幫助我嗎?
避免使用asInstanceOf不安全 – Pavel
謝謝! @ Cyeegha,之前我沒有看到這個問題,實際上我的問題也是一樣的。 – Yang
通常你應該返回Option [Node],然後使用模式匹配來查看結果是什麼 – Pavel