在Ruby中我可以这样写:我如何在Scala范围内进行模式匹配?
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
如何在斯卡拉做到这一点?
编辑:最好我想比使用if
更优雅。
在Ruby中我可以这样写:我如何在Scala范围内进行模式匹配?
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
如何在斯卡拉做到这一点?
编辑:最好我想比使用if
更优雅。
内侧的图案匹配它可以与卫兵表示:
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
请注意,包含实例应以首字母大写命名。如果不这样做,你需要在反引号给名称(这里很难,除非有一种逃避,我不知道)
对于相同大小的范围,你可以用老派的数学做到这一点:
val a = 11
(a/10) match {
case 0 => println (a + " in 0-9")
case 1 => println (a + " in 10-19") }
11 in 10-19
是的,我知道:“不要没有neccessity鸿沟” 但是:除以等于!
类似@亚丹娜的答案,但使用基本比较:
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"
}
也适用于浮动点n
请参阅相关的计算器问题:能否在范围在斯卡拉相匹配?(HTTP: //stackoverflow.com/questions/1346127/can-a-range-be-matched-in-scala) – 2011-09-26 01:35:56