首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >模式匹配序列理解的惯用方法是什么?

模式匹配序列理解的惯用方法是什么?
EN

Stack Overflow用户
提问于 2012-07-16 19:10:05
回答 2查看 11.5K关注 0票数 20
代码语言:javascript
复制
val x = for(i <- 1 to 3) yield i
x match {
    case 1 :: rest => ... // compile error
}

构造函数不能实例化为预期的类型;找到:集合.immutable。::B必需: scala.collection.immutable.IndexedSeqInt

这是与MatchError when match receives an IndexedSeq but not a LinearSeq相同的问题。

问题是,怎样做才是正确的?到处添加.toList似乎并不正确。如果创建一个自己的提取器来处理每个Seq (如另一个问题的答案中所述),如果每个人都这样做,将会导致混乱……

我想问题是,为什么我不能影响序列理解的返回类型,或者:为什么标准库中没有这样一个通用的Seq提取器?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-16 19:20:10

你可以对任何序列进行模式匹配:

代码语言:javascript
复制
case Seq(a, b, rest @ _ *) =>

例如:

代码语言:javascript
复制
scala> def mtch(s: Seq[Int]) = s match { 
  |      case Seq(a, b, rest @ _ *) => println("Found " + a + " and " + b)
  |      case _ => println("Bah") 
  |    }
mtch: (s: Seq[Int])Unit

然后,这将匹配任何超过(或等于)2个元素的序列

代码语言:javascript
复制
scala> mtch(List(1, 2, 3, 4))
Found 1 and 2

scala> mtch(Seq(1, 2, 3))
Found 1 and 2

scala> mtch(Vector(1, 2))
Found 1 and 2

scala> mtch(Vector(1))
Bah
票数 35
EN

Stack Overflow用户

发布于 2018-11-22 23:17:54

REPL中的Vector还有一个解决方案:

代码语言:javascript
复制
Vector() match {
    case a +: as => "head + tail"
    case _       => "empty"  
}
 res0: String = "empty"

Vector(1,2) match {
  case a +: as => s"$a + $as"
  case _      => "empty"  }
res1: String = 1 + Vector(2)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11503033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档