【问题标题】:Scala placeholder in array for pattern match [duplicate]用于模式匹配的数组中的Scala占位符[重复]
【发布时间】:2017-05-26 07:23:59
【问题描述】:

我要匹配第一个元素为 0 或 1 或 Null 的 Array,示例如下:

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 不安全
  • 谢谢! @Cyäegha,我之前没有看到这个问题,实际上我的问题是一样的。
  • 通常你应该返回 Option[Node] 然后使用模式匹配看看结果是什么
  • 谢谢,我会修改它,还有一个问题,为什么 asInstanceOf 不安全?
  • 这里有一些关于此的 cmets:stackoverflow.com/questions/6686992/… 根据我的理解,如果对象为 Null,asInstanceOf 只会抛出异常,这不是处理对象的“惯用”方式:

标签: arrays scala pattern-matching


【解决方案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)
    }
    
  • 在模式匹配中使用 if 守卫,如下所示

    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)
    }
    

【讨论】:

  • 感谢十亿,转换成List是个不错的选择。
  • 使用@_* => Array(head, tail @_*) insted 将数组转换为列表
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 2019-07-14
  • 2019-10-14
  • 2017-12-16
  • 2014-08-27
  • 2018-03-26
相关资源
最近更新 更多