Scala 使用模式匹配获取列表的第一个和最后一个元素 [英] Scala Get First and Last elements of List using Pattern Matching

查看:33
本文介绍了Scala 使用模式匹配获取列表的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对列表进行模式匹配.无论如何我可以访问列表的第一个和最后一个元素进行比较?

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?

我想做类似的事情..

case List(x, _*, y) if(x == y) => true

case x :: _* :: y =>

或类似的东西...其中 xy 是列表的第一个和最后一个元素..

or something similar... where x and y are first and last elements of the list..

我该怎么做……有什么想法吗?

How can I do that.. any Ideas?

推荐答案

使用标准 :++: 来自 scala.collection 包的提取器

Use the standard :+ and +: extractors from the scala.collection package

原答案

定义自定义提取器对象.

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)
  }
}

可以用作:

val first :: (l :+ last) = List(3, 89, 11, 29, 90)
println(first + " " + l + " " + last) // prints 3 List(89, 11, 29) 90

(对于你的情况:case x :: (_ :+ y) if(x == y) => true)

这篇关于Scala 使用模式匹配获取列表的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆