Consider a piece of code:
def foo(xs: Seq[Int]) = xs match {
case Nil => "empty list"
case head :: Nil => "one element list"
case head :: tail => s"head is $head and tail is $tail"
}
val x1 = Seq(1,2,3)
println(foo(x1))
val x2 = Seq()
println(foo(x2))
val x3 = Seq(1)
println(foo(x3))
val problem = 1 to 10
println(foo(problem))
A problem occurs, when we try to match a Range in foo(problem)
.
scala.MatchError: Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (of class scala.collection.immutable.Range$Inclusive)
.
Converting Range to Seq with val problem = (1 to 10).toSeq
is useless, as the toSeq
method just returns the Range itself:
override def toSeq = this
.
A workaround can be used:
val problem = (1 to 10).toList.toSeq
,
but it's not exactly the prettiest thing I've seen.
What is the proper way to match a Range to [head:tail] pattern?