可以在Scala中匹配范围吗?

时间:2009-08-28 10:18:31

标签: scala pattern-matching range matching

是否可以匹配Scala中的一系列值?

例如:

val t = 5
val m = t match {
    0 until 10 => true
    _ => false
}
如果m介于0和10之间,则

truet,否则为false。这一点当然不起作用,但有没有办法实现类似的东西?

5 个答案:

答案 0 :(得分:75)

使用Range保护:

val m = t match {
  case x if 0 until 10 contains x => true
  case _ => false
}

答案 1 :(得分:31)

你可以使用警卫:

val m = t match {
    case x if (0 <= x && x < 10) => true
    case _ => false
}

答案 2 :(得分:3)

以下是使用范围匹配的另一种方法:

val m = t match {
  case x if ((0 to 10).contains(x)) => true
  case _ => false
}

答案 3 :(得分:3)

有了这些定义:

  trait Inspector[-C, -T] {
    def contains(collection: C, value: T): Boolean
  }

  implicit def seqInspector[T, C <: SeqLike[Any, _]] = new Inspector[C, T]{
    override def contains(collection: C, value: T): Boolean = collection.contains(value)
  }

  implicit def setInspector[T, C <: Set[T]] = new Inspector[C, T] {
    override def contains(collection: C, value: T): Boolean = collection.contains(value)
  }

  implicit class MemberOps[T](t: T) {
    def in[C](coll: C)(implicit inspector: Inspector[C, T]) =
      inspector.contains(coll, t)
  }

您可以执行以下检查:

2 in List(1, 2, 4)      // true
2 in List("foo", 2)     // true
2 in Set("foo", 2)      // true
2 in Set(1, 3)          // false
2 in Set("foo", "foo")  // does not compile
2 in List("foo", "foo") // false (contains on a list is not the same as contains on a set)
2 in (0 to 10)          // true

所以你需要的代码是:

val m = x in (0 to 10)

答案 4 :(得分:0)

另一种选择是使用implicits将其添加到语言中,我为int和Range添加了两个变体

object ComparisonExt {
  implicit class IntComparisonOps(private val x : Int) extends AnyVal {
    def between(range: Range) = x >= range.head && x < range.last
    def between(from: Int, to: Int) = x >= from && x < to
  }

}

object CallSite {
  import ComparisonExt._

  val t = 5
  if (t between(0 until 10)) println("matched")
  if (!(20 between(0 until 10))) println("not matched")
  if (t between(0, 10)) println("matched")
  if (!(20 between(0, 10))) println("not matched")
}