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

查看:126
本文介绍了除列表之外的序列上的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,但编译器提示错误:not found:value +:'

  • 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的答案,因为他是第一个,注意::不是我的例子中的运算符,而是一个case类,因此的区别。

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天全站免登陆