Skip to content

Extractor for pattern matching last element of a list #2575

Closed

Description

@scabug

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.

Activity

  1. scabug commented on Nov 4, 2009

    @scabug
    Author

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

  2. scabug commented on Nov 17, 2009

    @scabug
    Author

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

  3. scabug commented on Dec 4, 2012

    @scabug
    Author

    @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
  4. added this to the 2.10.0 milestone on Apr 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions