Scala 允许这种提取器吗?
假设我有这个集合:
val a = Array(Array(1,2,3,4,5),Array(4,5),Array(5),Array(1,2,6,7,8))
有没有一种方法可以定义一个提取器,它可以按以下方式工作:
a.foreach(e => {
e match {
case Array( ending with 5 ) =>
case _ =>
}
})
抱歉伪代码,但我不知道如何表达它。有没有办法匹配最后一个元素为 5 的内容?如果我想匹配第一个元素为 1、最后一个元素为 5 的内容该怎么办?这是否适用于各种长度的数组(请注意,我在示例中专门为数组选择了不同的长度)。
谢谢!
Let's say I have this collection:
val a = Array(Array(1,2,3,4,5),Array(4,5),Array(5),Array(1,2,6,7,8))
Is there a way to define an extractor which would work in the following way:
a.foreach(e => {
e match {
case Array( ending with 5 ) =>
case _ =>
}
})
Sorry for the pseudocode, but I don't know how to express it. Is there a way to match something having 5 as the last element? What if I would want to match something having a 1 as the first element and a 5 as the last? Could this work for arrays of various lengths ( note that I specifically chose different lengths for my arrays in the example ).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以:
在您的示例中:
它按预期打印
(1,2,3,4,5)
、(4,5)
和(5)
使用相同的方法,您可以编写一个提取器
StartWith
,然后添加一个方法将它们组合到一个匹配这两个条件的新提取器中。Yes you can:
On your example:
It prints as expected
(1,2,3,4,5)
,(4,5)
and(5)
With the same approach, you could write an extractor
StartWith
and then add a method to combine them in a new extractor matching both conditions.您可以做一些更好的事情来匹配第一个元素:
不幸的是,
@_*
必须是数组参数列表中的最后一项。但您可以根据需要使之前的匹配变得尽可能复杂。You can do something a little better for matching on the first elements:
Unfortunately the
@_*
thing has to be the last item in the list of array arguments. But you can make the matching before that as complex as you want.case
语法支持if
,因此这样可以工作:The
case
syntax supportsif
s, so this would work:为什么不直接匹配最后一个元素?
Why don't you match directly for the last element?