What is the idiomatic way to pattern match sequence comprehensions?

十年热恋 提交于 2019-11-27 14:37:22

问题


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

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

This is the same problem as MatchError when match receives an IndexedSeq but not a LinearSeq.

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...

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?


回答1:


Well, you can pattern-match any sequence:

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

For example:

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

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



回答2:


One more solution for Vector in REPL:

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)


来源:https://stackoverflow.com/questions/11503033/what-is-the-idiomatic-way-to-pattern-match-sequence-comprehensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!