How can I pattern match on a range in Scala?

2019-01-14 10:44发布

问题:

In Ruby I can write this:

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?

Edit: preferably I'd like to do it more elegantly than using if.

回答1:

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


回答2:

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)



回答3:

Similar to @Yardena's answer, but using basic comparisons:

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



回答4:

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!