模式匹配scala中的常量表达式?

时间:2012-12-07 19:11:48

标签: scala pattern-matching

是否可以重写以下代码

for (i <- x) {
  if (i==x.first) {
    // do sth
  } else if (i==x.last) {
    // do sth
  } else {
    // do sth
  }
}

使用类似

的模式匹配
for (i <- x) i match { 
  case `x.first` => // do sth
  case `x.last` => // do sth
  case _ => // do sth
}

我知道我们可以使用后卫,或提前评估x.firstx.last并将其存储在其他val中以引用此处,但这只是丑陋的。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:5)

一种干净的方法是为自己定义提取器+::+

object +: {
  def unapply[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): Option[(A, That)] = {
    if (seq.nonEmpty)
      Some(seq.head, cbf(seq) ++= seq.tail result)
    else
      None
  }
}

object :+ {
  def unapply[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): Option[(That, A)] = {
    if (seq.nonEmpty)
      Some(cbf(seq) ++= seq.dropRight(1) result, seq.last)
    else
      None
  }
}

然后你就可以做到:

val x = Seq(1, 2, 3, 4)
val first +: middle :+ last = x

println("first is %s".format(first))
for (y <- middle)
  println("middle contains %s".format(y))
println("last is %s".format(last))

打印哪些:

first is 1
middle contains 2
middle contains 3
last is 4