2017-05-26 59 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