模式匹配“case Nil"向量 [英] Pattern Matching "case Nil" for Vector
问题描述
阅读此帖子后,了解如何在Vector
(或任何集合)上使用模式匹配实现了 Seq
),我在这个集合上测试了模式匹配.
After reading this post on how to use pattern matching on Vector
(or any collection that implements Seq
), I tested pattern matching on this collection.
scala> x // Vector
res38: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
scala> x match {
| case y +: ys => println("y: " + "ys: " + ys)
| case Nil => println("empty vector")
| }
<console>:12: error: pattern type is incompatible with expected type;
found : scala.collection.immutable.Nil.type
required: scala.collection.immutable.Vector[Int]
Note: if you intended to match against the class, try `case _: <none>`
case Nil => println("empty vector")
^
这里是 dhg
的回答,解释了 +:
:
Here's dhg
's answer that explains +:
:
object +: {
def unapply[T](s: Seq[T]) =
s.headOption.map(head => (head, s.tail))
}
REPL
告诉我
scala> Vector[Int]() == Nil
res37: Boolean = true
...那么为什么我不能将这个 case Nil
语句用于 Vector
?
... so why can I not use this case Nil
statement for an Vector
?
推荐答案
比较 Vector[Int]() == Nil
是可能的,因为您比较的内容在类型级别上没有限制;另一方面,它允许集合的 equals
实现,无论集合类型如何,都可以逐个元素地进行比较:
The comparison Vector[Int]() == Nil
is possible because there is no constraint on the type level for what you compare; that allows the implementation of equals
for collections, on the other hand, to perform an element by element comparison irrespective of the collection type:
Vector(1, 2, 3) == List(1, 2, 3) // true!
在模式匹配中,当类型与列表无关(它是一个 Vector
)时,你不能有一个空列表(Nil
)的情况.
In pattern matching, you cannot have a case for an empty list (Nil
) when the type is not related to list (it's a Vector
).
你可以这样做:
val x = Vector(1, 2, 3)
x match {
case y +: ys => println("head: " + y + "; tail: " + ys)
case IndexedSeq() => println("empty vector")
}
但我建议在这里只使用默认情况,因为如果 x
没有 head 元素,它在技术上必须是空的:
But I would suggest just to use the default case here, because if x
does not have a head element, it must be technically empty:
x match {
case y +: ys => println("head: " + y + "; tail: " + ys)
case _ => println("empty vector")
}
这篇关于模式匹配“case Nil"向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!