模式匹配序列理解的惯用方式是什么? [英] What is the idiomatic way to pattern match sequence comprehensions?

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

问题描述

val x = for(i <- 1 to 3) yield i
x match {
    case 1 :: rest => ... // compile error
}

构造函数不能实例化为期望的类型;成立 : collection.immutable.::[B]必需: scala.collection.immutable.IndexedSeq [Int]

constructor cannot be instantiated to expected type; found : collection.immutable.::[B] required: scala.collection.immutable.IndexedSeq[Int]

这与 MatchError匹配时存在相同的问题收到IndexedSeq而不是LinearSeq .

问题是,如何正确执行?在任何地方添加.toList似乎都不正确.并且创建一个处理每个Seq的自己的提取器(如另一个问题的答案中所述),如果每个人都这样做会导致混乱……

The question is, how to do it right? Adding .toList everywhere doesn't seem right. And creating an own extractor which handles every Seq (as described in the answer of the other question) would lead to a mess if everybody would do it...

我想的问题是,为什么我不能影响序列理解的返回类型是什么,或者:为什么标准库中的这种广义的Seq提取器部分不起作用?

I guess the question is, why can't I influence what the return type of sequence comprehensions is, or: why isn't such a generalized Seq extractor part of the standard library?

推荐答案

好,您可以对任何序列进行模式匹配:

Well, you can pattern-match any sequence:

case Seq(a, b, rest @ _ *) =>

例如:

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个以上元素的任何序列

Then this will match any sequence with more than (or equal to) 2 elements

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

这篇关于模式匹配序列理解的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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