可以在 Scala 中匹配范围吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1346127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:37:57  来源:igfitidea点击:

Can a range be matched in Scala?

scalapattern-matchingrangematching

提问by Justin Poliey

Is it possible to match a range of values in Scala?

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

For example:

例如:

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

mwould be trueif twas between 0 and 10, but false otherwise. This little bit doesn't work of course, but is there any way to achieve something like it?

mtrue,如果t为0和10,但假另有。这一点当然行不通,但是有没有办法实现类似的目标?

回答by Alexander Azarov

Guard using Range:

守卫使用Range

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

回答by Alexey Romanov

You can use guards:

您可以使用警卫:

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

回答by swartzrock

Here's another way to match using a range:

这是使用范围进行匹配的另一种方法:

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

回答by Wilfred Springer

With these definitions:

有了这些定义:

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

You can do checks like these:

你可以做这样的检查:

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

So the code you need would be:

所以你需要的代码是:

val m = x in (0 to 10)

回答by Noam

Another option would be to actually add this to the language using implicits, i added two variations for int and Range

另一种选择是使用隐式将其实际添加到语言中,我为 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")
}