Why does this list matcher not working as expected?
I am practicing to use extractor:
scala> object LE {
| def unapply[A](theList: List[A]) =
| if (theList.size == 0) None
| else Some((theList.head, theList.tail))
| }
defined module LE
It works for matching one element:
scala> List(0, 1, 2) match {
| case head LE more => println(head, more)
| }
(0,List(1, 2))
But does not appear to work for matching more than one element:
scala> List(0, 1, 2) match {
| case head LE next LE more => println(head, more)
| }
<console>:10: error: scrutinee is incompatible with pattern type;
found : List[A]
required: Int
My list extractor looks very similar to Scala's Stream extractor, which
can be used like this:
val xs = 58 #:: 43 #:: 93 #:: Stream.empty
xs match {
case first #:: second #:: _ => first - second
case _ => -1
}
So what difference prevents my LE from being used in such a way?
No comments:
Post a Comment