除列表之外的序列上的 Scala 模式匹配

标签 scala collections pattern-matching

我有以下代码,它对列表中的每个元素进行递归操作

def doMatch(list: List[Int]): Unit = list match {
  case last :: Nil  => println("Final element.")
  case head :: tail => println("Recursing..."); doMatch(tail)
}

现在,忽略这个功能可以通过 filter()foreach() 获得,这工作得很好。但是,如果我尝试更改它以接受任何 Seq[Int],我会遇到问题:

  • Seq 没有​​::,但它有 +:,据我了解,这基本上是同一件事。但是,如果我尝试在 head +: tail 上匹配,编译器会提示“错误:未找到:值+:”
  • Nil 是 List 特有的,我不知道用什么来替换它。如果我解决了上一个问题,我将尝试 Seq()

我认为代码应该是这样的,但它不起作用:

def doMatch(seq: Seq[Int]): Unit = seq match {
  case last +: Seq() => println("Final element.")
  case head +: tail  => println("Recursing..."); doMatch(tail)
}

编辑:这么多好的答案!我接受agilesteel的答案,因为他是第一个指出::在我的示例中不是运算符,而是案例类,因此存在差异的答案。

最佳答案

截至 2012 年 3 月的 IDE,这适用于 2.10+:

  def doMatch(seq: Seq[Int]): Unit = seq match {
    case last +: Seq() => println("Final element.")
    case head +: tail  => println("Recursing..."); doMatch(tail)
  }                                               //> doMatch: (seq: Seq[Int])Unit

  doMatch(List(1, 2))                             //> Recursing...
                                                  //| Final element.

更一般地说,为 SeqExtractors 中的 Seq 添加了两个不同的 head/tail 和 init/last 分解对象,镜像附加/前置。 :

List(1, 2) match { case init :+ last => last } //> res0: Int = 2                                              
List(1, 2) match { case head +: tail => tail } //> res1: List[Int] = List(2)                                               
Vector(1, 2) match { case init :+ last => last } //> res2: Int = 2                                              
Vector(1, 2) match { case head +: tail => tail } //> res3: scala.collection.immutable.Vector[Int] = Vector(2)

关于除列表之外的序列上的 Scala 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807540/

相关文章:

swift - 从 Collection View 执行segue

haskell - Haskell 中数据族的模式匹配

scala - 如何在akka的发送和接收 Action 中添加日志功能

arrays - Scala:将两个数组合并为一个结构

java - HashSet是通过HashMap实例实现的

java - 如何使用来自哈希集的参数调用方法?

str_detect 中的正则表达式?

scala - Scala 匿名函数中的模式匹配

java - Scala:ArrayBuffer/ArrayList 的 Json 表示...如何避免打印出集合中的空信息?

Scala 使多选项检查更加简洁