1

我正在练习使用提取器:

scala> object LE {
     | def unapply[A](theList: List[A]) = 
     | if (theList.size == 0) None
     | else Some((theList.head, theList.tail))
     | }
defined module LE

它适用于匹配一个元素:

scala> List(0, 1, 2) match {
     | case head LE more => println(head, more)
     | }
(0,List(1, 2))

但似乎不适用于匹配多个元素:

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

我的列表提取器看起来非常类似于 Scala 的 Stream 提取器,可以这样使用:

val xs = 58 #:: 43 #:: 93 #:: Stream.empty
xs match {
  case first #:: second #:: _ => first - second
  case _ => -1
}

那么有什么区别可以阻止我的 LE 以这种方式使用呢?

4

1 回答 1

3

问题是执行顺序。对于#::,因为它以 结尾:,Scala 对其进行了特殊处理,从右到左而不是从左到右关联(对于任何其他运算符/类型来说都是正常的,例如 your LE)。以下工作如您所料:

scala> List(0, 1, 2) match {
     | case head LE (next LE more) => println(head, more)
     | }
(0,List(2))
于 2013-08-19T00:37:13.270 回答