使用视图时匹配错误
List(1,2,3,4).sliding(2).map({ case List(a, b) => a < b }).forall(identity)
编译并返回 true
(尽管有一个匹配不详尽的警告)。
List(1,2,3,4).view
.sliding(2).map({ case List(a: Int, b: Int) => a < b }).forall(identity)
编译(只要我们包含 a
和 b
的类型注释),但会抛出 MatchError:
scala.MatchError: SeqViewC(...) (of class scala.collection.SeqViewLike$$anon$1)
at $anonfun$1.apply(<console>:12)
at $anonfun$1.apply(<console>:12)
at scala.collection.Iterator$$anon$19.next(Iterator.scala:335)
at scala.collection.Iterator$class.forall(Iterator.scala:663)
at scala.collection.Iterator$$anon$19.forall(Iterator.scala:333)
Why?
List(1,2,3,4).sliding(2).map({ case List(a, b) => a < b }).forall(identity)
compiles and returns true
(albeit with a warning that the match is not exhaustive).
List(1,2,3,4).view
.sliding(2).map({ case List(a: Int, b: Int) => a < b }).forall(identity)
compiles (so long as we include the type annotations for a
and b
) but throws a MatchError:
scala.MatchError: SeqViewC(...) (of class scala.collection.SeqViewLike$anon$1)
at $anonfun$1.apply(<console>:12)
at $anonfun$1.apply(<console>:12)
at scala.collection.Iterator$anon$19.next(Iterator.scala:335)
at scala.collection.Iterator$class.forall(Iterator.scala:663)
at scala.collection.Iterator$anon$19.forall(Iterator.scala:333)
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的是,列表提取器
List.unapplySeq
无法提取SeqViewLike
对象,这就是您收到匹配错误的原因。但另一方面,Seq
可以。您可以这样看到:因此,对第二行的修复是:
所以问题是
List(1,2,3,4).view
返回一个SeqView
。请注意,
sliding
已经返回一个Iterator
,因此 List(1,2,3,4).sliding(2) 是惰性的。可能view
不是必需的。That's interesting, the list extractor
List.unapplySeq
is not able to extractSeqViewLike
objects, which is why you get a match error. But on the other handSeq
can. You can see that like this:So a fix to your second line would be:
So the issue is that
List(1,2,3,4).view
returns aSeqView
.Note that
sliding
already returns anIterator
, so List(1,2,3,4).sliding(2) is lazy is that sense. May beview
is not necessary.好吧,列表的视图不是列表,它是一个 SeqView,它是一个 Seq。下面的做法是正确的:
Well, a view of a list is not a list, it is a SeqView, which is a Seq. The following does the right thing: