了解列表上的模式匹配
我最近一直在玩提取器,想知道列表提取器是如何工作的,尤其是这个:
List(1, 2, 3) match {
case x :: y :: z :: Nil => x + y + z // case ::(x, ::(y, ::(z , Nil)))
}
Ok :: 在模式中使用,所以我猜编译器现在在 ::-Object 中查找 unapply 方法。所以尝试了这个:
scala> (::).unapply(::(1, ::(2, Nil)))
res3: Option[(Int, List[Int])] = Some((1,List(2)))
很好,有效。然而这并没有:
scala> (::).unapply(List(1,2,3))
<console>:6: error: type mismatch;
found : List[Int]
required: scala.collection.immutable.::[?]
(::).unapply(List(1,2,3))
而这却是:
scala> List.unapplySeq(List(1,2,3))
res5: Some[List[Int]] = Some(List(1, 2, 3))
实际上我现在有点困惑。这里编译器如何选择 unapply 的正确实现。
I've been playing around with Extractors lately and was wondering how the List extractors work especially this:
List(1, 2, 3) match {
case x :: y :: z :: Nil => x + y + z // case ::(x, ::(y, ::(z , Nil)))
}
Ok :: is used in the pattern, so I guess that the compiler now looks up the unapply method in the ::-Object. So tried this:
scala> (::).unapply(::(1, ::(2, Nil)))
res3: Option[(Int, List[Int])] = Some((1,List(2)))
Nice that works. However this does not:
scala> (::).unapply(List(1,2,3))
<console>:6: error: type mismatch;
found : List[Int]
required: scala.collection.immutable.::[?]
(::).unapply(List(1,2,3))
while this does:
scala> List.unapplySeq(List(1,2,3))
res5: Some[List[Int]] = Some(List(1, 2, 3))
Actually I'm a little puzzled at the moment. How does the compiler choose the right implementation of unapply here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Match 基本上执行以下操作:
一旦它知道它是安全的(因为
List(1,2,3).isInstanceOf[::[Int]]
是true
)。Match is basically doing the following:
once it knows that it's safe (because
List(1,2,3).isInstanceOf[::[Int]]
istrue
).