列表以外的序列上的 Scala 模式匹配 [英] Scala pattern matching on sequences other than Lists

查看:16
本文介绍了列表以外的序列上的 Scala 模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code which recursively operates on each element within a List

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],则会遇到问题:

Now, ignoring that this functionality is available through filter() and foreach(), this works just fine. However, if I try to change it to accept any Seq[Int], I run into problems:

  • Seq 没有​​ ::,但它有 +:,据我所知,这基本上是一样的.但是,如果我尝试在 head +: tail 上进行匹配,则编译器会抱怨错误:未找到:值 +:"
  • Nil 特定于 List,我不确定用什么来替换它.如果我解决了之前的问题,我将尝试 Seq()

以下是我认为代码的外观,但它不起作用:

Here is how I think the code should look, except it doesn't work:

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

这么多好的答案!我接受了agilesteel 的回答,因为他是第一个指出 :: 在我的示例中不是运算符,而是案例类,因此是不同的.

So many good answers! I'm accepting agilesteel's answer as his was the first that noted that :: isn't an operator in my example, but a case class and hence the difference.

推荐答案

Scala 中有两个 ::(发音为 cons).一个是class List 中定义的操作符,一个是class(List的子类),表示一个有头有尾的非空列表.

There are two :: (pronounced cons) in Scala. One is an operator defined in class List and one is a class (subclass of List), which represents a non empty list characterized by a head and a tail.

head :: tail 是一个构造器模式,它是从 ::(head, tail) 语法修改而来的.

head :: tail is a constructor pattern, which is syntactically modified from ::(head, tail).

:: 是一个 case 类,这意味着为它定义了一个提取器对象.

:: is a case class, which means there is an extractor object defined for it.

这篇关于列表以外的序列上的 Scala 模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆