Scala使用模式匹配获取列表的第一个和最后一个元素 [英] Scala Get First and Last elements of List using Pattern Matching
本文介绍了Scala使用模式匹配获取列表的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在列表上进行模式匹配。无论如何,我可以访问列表的第一个和最后一个元素进行比较?
我想做类似的事情。
case List x,_ *,y)if(x == y)=> true
或
case x :: _ * :: y =>
或类似的东西...
其中 x
和 y
是列表中的第一个和最后一个元素..
我该怎么做..任何想法?
scala-lang.org/api/current/#scala.collection.$colon$plus$rel =nofollow>:+ 和 +:从 scala.collection
package p> 原始答案
定义
object:+ {
def unapply [A](l:List [A]):选项[(List [A],A)] = {
if(l.isEmpty)
None
else
某些(l.init,l.last)
$ / code $ / pre
可用作:
val first ::(l:+ last)= List(3,89,11,29,90)
println(first ++ l ++ last)//打印3列表(89,11,29)90
<您的情况: case x ::(_:+ y)if(x == y)=>真正的
)
I am doing a pattern matching on a list. Is there anyway I can access the first and last element of the list to compare?
I want to do something like..
case List(x, _*, y) if(x == y) => true
or
case x :: _* :: y =>
or something similar...
where x
and y
are first and last elements of the list..
How can I do that.. any Ideas?
解决方案 Use the standard :+ and +: extractors from the scala.collection
package
ORIGINAL ANSWER
Define a custom extractor object.
object :+ {
def unapply[A](l: List[A]): Option[(List[A], A)] = {
if(l.isEmpty)
None
else
Some(l.init, l.last)
}
}
Can be used as:
val first :: (l :+ last) = List(3, 89, 11, 29, 90)
println(first + " " + l + " " + last) // prints 3 List(89, 11, 29) 90
(For your case: case x :: (_ :+ y) if(x == y) => true
)
这篇关于Scala使用模式匹配获取列表的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文