简体   繁体   English

如何在Scala中的范围上进行模式匹配?

[英]How can I pattern match on a range in Scala?

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更优雅。

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"
}
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. 请注意,Contains实例应以初始大写字母命名。 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) 如果你不这样做,你需要在后面引用这个名字(这里很难,除非有一个我不知道的逃脱)

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

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! 但是:Divide et impera!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM