可在范围在斯卡拉相匹配?(Can a range be matched in Scala?)

2019-07-04 00:00发布

是否有可能匹配斯卡拉值的范围?

例如:

val t = 5
val m = t match {
    0 until 10 => true
    _ => false
}

m将是true如果t是0和10,但假之间否则。 这一点并不当然的工作,但有什么办法来实现类似的东西?

Answer 1:

后卫使用Range

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


Answer 2:

您可以使用卫士:

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


Answer 3:

这里有另一种使用范围来匹配:

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


Answer 4:

随着这些定义:

  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)


Answer 5:

另一种选择是将其实这添加到使用implicits的语言,我增加了对INT和范围内的两个变化

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")
}


文章来源: Can a range be matched in Scala?