Does Scala provide this kind of extractor?

Let's say I have this collection:

val a = Array(Array(1,2,3,4,5),Array(4,5),Array(5),Array(1,2,6,7,8))

Is there a way to define an extractor that will work as follows:

a.foreach(e => {
   e match {
      case Array( ending with 5 ) => 
      case _ =>
   }
})

Sorry for the pseudo-code, but I don't know how to express it. Is there a way to match something having 5 as the last element? What if I want to match something that has 1 as the first element and 5 as the last? Can this work for arrays of different lengths (note that I specifically chose different lengths for my arrays in the example).

Thank!

+5
source share
4 answers
a.foreach(e => {
   e match {
      case a: Array[Int] if a.last == 5 => 
      case _ =>
   }
})

You can do something a little better for matching on the first elements:

a.foreach(e => {
   e match {
      case Array(1, _*) => 
      case _ => 
   }
})

, @_* . , .

scala> val Array(1, x @_*) = Array(1,2,3,4,5)
x: Seq[Int] = Vector(2, 3, 4, 5)

scala> val Array(1, b, 3, x @_*) = Array(1,2,3,4,5)
b: Int = 2
x: Seq[Int] = Vector(4, 5)
+9

, :

object EndsWith {
  def unapply[A]( xs: Array[A] ) = 
    if( xs.nonEmpty ) Some( xs.last ) else None
}

:

val a = Array(Array(1,2,3,4,5),Array(4,5),Array(5),Array(1,2,6,7,8))

a foreach { 
  case e @ EndsWith(5) => println( e.mkString("(",",",")" ) )
  case _ =>
}

(1,2,3,4,5), (4,5) (5)

, StartWith, , .

+11

The syntax casesupports ifs, so this will work:

a foreach {
  case a: Array[Int] if a.last == 5 =>
  case _ =>
}
+4
source
a.foreach (ar => ar.last match {                    
  case 5 => println ("-> 5] " + ar.mkString ("~"))
  case _ => println ("   ?] " + ar.mkString (":")) }) 

Why aren't you directly responsible for the last item?

-> 5] 1~2~3~4~5
-> 5] 4~5
-> 5] 5
   ?] 1:2:6:7:8
+1
source

All Articles