2010-07-01 7 views
30

In Ruby kann ich schreiben:Wie kann ich Muster in einem Bereich in Scala zusammenbringen?

case n 
when 0...5 then "less than five" 
when 5...10 then "less than ten" 
else "a lot" 
end 

Wie kann ich dies in Scala?

Edit: vorzugsweise würde ich es eleganter tun als mit if.

+2

eine verwandte Stackoverflow Frage Siehe: [Kann ein Bereich, in Scala angepasst werden?] (Http: //stackoverflow.com/questions/1346127/can-a-range-be-matches-in-scala) –

Antwort

56

Innenmustererkennung kann es mit Wachen ausgedrückt werden:

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

Beachten Sie, dass Contains-Instanzen mit Anfangsbuchstaben benannt werden sollten. Wenn Sie dies nicht tun, müssen Sie den Namen in Back-Zitate (schwer hier, es sei denn, eine Flucht ist, weiß ich nicht) geben

4

für Bereiche gleicher Größe, können Sie es mit der alten Schule Mathematik tun:

val a = 11 
(a/10) match {      
    case 0 => println (a + " in 0-9") 
    case 1 => println (a + " in 10-19") } 

11 in 10-19 

Ja, ich weiß: „Sie ohne neccessity nicht teilen“ Aber: Divide et impera!

8

ähnlich @ Yardena Antwort, aber mit einfachen Vergleiche:

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

funktionieren auch für Gleitkomma n