[英]How can I pattern match on a range in Scala?
在Ruby中我可以這樣寫:
case n
when 0...5 then "less than five"
when 5...10 then "less than ten"
else "a lot"
end
我如何在Scala中執行此操作?
編輯:我最好比使用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
請注意,Contains實例應以初始大寫字母命名。 如果你不這樣做,你需要在后面引用這個名字(這里很難,除非有一個我不知道的逃脫)
與@ 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"
}
也適用於浮點數n
對於相同大小的范圍,您可以使用舊式數學來完成:
val a = 11
(a/10) match {
case 0 => println (a + " in 0-9")
case 1 => println (a + " in 10-19") }
11 in 10-19
是的,我知道:“不要在沒有必要的情況下分開!” 但是:Divide et impera!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.