模式匹配具有范围的 Seq [英] Pattern match a Seq with Range
问题描述
考虑一段代码:
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))
出现问题,当我们尝试匹配 foo(problem)
中的 Range 时.
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)(类 scala.collection.immutable.Range$Inclusive)
.
Converting Range to Seq with val problem = (1 to 10).toSeq
没用,因为 toSeq
方法只返回 Range 本身:
Converting Range to Seq with val problem = (1 to 10).toSeq
is useless, as the toSeq
method just returns the Range itself:
覆盖 def toSeq = this
.
可以使用一种解决方法:
A workaround can be used:
val 问题 = (1 to 10).toList.toSeq
,
但这并不是我见过的最漂亮的东西.
but it's not exactly the prettiest thing I've seen.
将 Range 匹配到 [head:tail] 模式的正确方法是什么?
What is the proper way to match a Range to [head:tail] pattern?
推荐答案
您可以使用 +:
运算符.就像 ::
,除了它不仅适用于 List,还适用于任何 Seq.
You can use the +:
operator. It's like ::
, except instead of only being for List, it works on any Seq.
def foo(xs: Seq[Int]) = xs match {
case Seq() => "empty list"
case head +: Seq() => "one element list"
case head +: tail => s"head is $head and tail is $tail"
}
或者,更好的是,只需在 Seq
提取器上进行模式匹配:
Or, even better, just pattern match on the Seq
extractor:
def foo(xs: Seq[Int]) = xs match {
case Seq() => "empty list"
case Seq(head) => "one element list"
case Seq(head, tail @ _*) => s"head is $head and tail is $tail"
}
这篇关于模式匹配具有范围的 Seq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!