Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extractor for pattern matching last element of a list #2575

Closed
scabug opened this issue Nov 4, 2009 · 3 comments
Closed

Extractor for pattern matching last element of a list #2575

scabug opened this issue Nov 4, 2009 · 3 comments

Comments

@scabug
Copy link

scabug commented Nov 4, 2009

Scala has an elegant way to match the first element of a list, but not the last one. Doing it currently seems fairly awkward:

List(1,2,3) match {
  case l: List[_] if l.last == 3 => println("last is 3")
}

Instead, Apache ESME has defined the following extractor to be able to match the last element of the list:

object ::> {
  def unapply[A] (l: List[A]) = l match {
    case Nil => None
    case _ => Some( (l.init, l.last) )
  }
}

Now one can simply do this

List(1,2,3) match {
  case _ ::> 3 => println("last is 3")
}

Does it make sense to include something like this in the standard library? Perhaps one could think of a more appropriate object name.

This feature request is definitely not of high priority.

@scabug
Copy link
Author

scabug commented Nov 4, 2009

Imported From: https://issues.scala-lang.org/browse/SI-2575?orig=1
Reporter: Vassil Dichev (vdichev)

@scabug
Copy link
Author

scabug commented Nov 17, 2009

@adriaanm said:
this should go to the greenhouse project that will be announced soon
you can easily do this outside of the std library

@scabug
Copy link
Author

scabug commented Dec 4, 2012

@retronym said:

~/code/scala squala
Welcome to Scala version 2.10.1-20121203-101839-fd57069a3a (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_27).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val init :+ last = List(1, 2, 3)
init: List[Int] = List(1, 2)
last: Int = 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants