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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With