Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Get First and Last elements of List using Pattern Matching

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?

like image 216
Teja Kantamneni Avatar asked Jul 14 '11 17:07

Teja Kantamneni


2 Answers

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)

like image 105
missingfaktor Avatar answered Oct 04 '22 22:10

missingfaktor


In case you missed the obvious:

case list @ (head :: tail) if head == list.last => true

The head::tail part is there so you don’t match on the empty list.

like image 45
Debilski Avatar answered Oct 04 '22 21:10

Debilski