Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala "match" help

I am studying some scala code and found this method which baffles me. In the match statement, what is the sublist@ construct? what kind of value does it contains? when I printed it its no diff than tail, but if I replace it with tail, the function returns diff result. Can somebody explain what it is and point me to a right resource to understand it? (I know I can search in google, but don't know what to look for..)

def flatMapSublists[A, B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
    ls match {
      case Nil => Nil
      case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
    }
like image 484
Teja Kantamneni Avatar asked Dec 22 '10 20:12

Teja Kantamneni


1 Answers

I would call it the "eat your cake and have it too operator". At any level in pattern matching, you can give a part a name (before the @) and deconstruct it further (after the @). For instance imagine you want to match against a List with 3 elements, you need the second element, but you want to log the whole list:

something match {
  case list@List(_,elem,_) => log("matching:" + list); elem    
  case _ => error("not found")
}   

Without this feature, you had to write something like

something match {
  case List(a,elem,b) => log("matching:" + List(a,elem,b)); elem    
  case _ => error("not found")
}   

As you can see, we need to name the first and third element, just because we need them to get a list with the same structure on the right side, which is boilerplate. It is much easier and clearer if you can give the whole thing a name (list), and parts deeper in the structure as well (elem), when you need both on the right side.

like image 177
Landei Avatar answered Oct 14 '22 19:10

Landei