如何在 Scala 的范围上进行模式匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3160888/
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
How can I pattern match on a range in Scala?
提问by Theo
In Ruby I can write this:
在 Ruby 中,我可以这样写:
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
How do I do this in Scala?
我如何在 Scala 中做到这一点?
Edit: preferably I'd like to do it more elegantly than using if.
编辑:我最好比使用if.
回答by Yardena
Inside pattern match it can be expressed with guards:
内部模式匹配可以用守卫来表达:
n match {
case it if 0 until 5 contains it => "less than five"
case it if 5 until 10 contains it => "less than ten"
case _ => "a lot"
}
回答by Randall Schulz
class Contains(r: Range) { def unapply(i: Int): Boolean = r contains i }
val C1 = new Contains(3 to 10)
val C2 = new Contains(20 to 30)
scala> 5 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C1
scala> 23 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
C2
scala> 45 match { case C1() => println("C1"); case C2() => println("C2"); case _ => println("none") }
none
Note that Contains instances should be named with initial caps. If you don't, you'll need to give the name in back-quotes (difficult here, unless there's an escape I don't know)
请注意,包含实例应使用初始大写字母命名。如果你不这样做,你需要在反引号中给出名称(这里很难,除非我不知道有一个转义)
回答by gens
Similar to @Yardena's answer, but using basic comparisons:
类似于@Yardena 的回答,但使用基本比较:
n match {
case i if (i >= 0 && i < 5) => "less than five"
case i if (i >= 5 && i < 10) => "less than ten"
case _ => "a lot"
}
Also works for floating point n
也适用于浮点 n
回答by user unknown
For Ranges of equal size, you can do it with old-school math:
对于相同大小的范围,您可以使用老式数学来完成:
val a = 11
(a/10) match {
case 0 => println (a + " in 0-9")
case 1 => println (a + " in 10-19") }
11 in 10-19
Yes, I know: "Don't divide without neccessity!" But: Divide et impera!
是的,我知道:“没有必要就不要分!” 但是:分而治之!

