2016-10-23 75 views
1

我需要用一大堆的比賽情況Scala中,我怎麼使用或如果匹配盒子內部,例如:邏輯,如果裏面的比賽情況斯卡拉

import scala.util.Random 

val x = Random.nextInt(30) 
val result = match x { 
case 0 to 10 => bad 
case 11 to 20 => average 
case 20 to 30 => cool 
} 

的第一個問題是怎麼做的我這樣做,而不是使用floor,ceil,round或其他數學的東西?

其次,對於字符串值,在PHP中,我們可以很容易地使用if (x == 'some')||(x == 'thing'){result}但這怎麼可以在scala匹配情況下工作?

例如當VAL x是隨機的A至I:

val result = match x { 
case A || B || C => bad 
case D || E || F => average 
case G || H || I => cool 
} 

謝謝!

+1

的可能的複製[?我怎樣才能在斯卡拉一系列模式匹配(http://stackoverflow.com/questions/3160888/how-can-i-pattern-match-on-a-範圍在斯卡拉) –

+0

但它不同@YuvalItz chakov我的問題還包括字符串,並且我認爲Pamu的答案比使用狀態好得多,如果狀態爲 –

+0

那裏的答案不使用'if-else'表達式。另外,從查看如何使用整數的警衛,你可以推斷出如何爲字符串做同樣的事情。 –

回答

3

這裏是一個更接近你的僞代碼的替代:

val x:Int 

val result = x match { 
    case x if (1 to 10).contains(x) => "bad" 
    case x if (11 to 20).contains(x) => "average" 
    case x if (21 to 30).contains(x) => "cool" 
    case _ => "unknown" 
} 


val y:String 

val result = y match { 
    case "A" | "B" | "C" => "bad" 
    case "D" | "E" | "F" => "average" 
    case "G" | "H" | "I" => "cool" 
    case _ => "unknown" 
} 

這將是更方便的治療字母分數作爲字符以利用範圍在第一個例子:

val z:Char 

val result = z match { 
    case x if ('A' to 'C').contains(x) => "bad" 
    case x if ('D' to 'F').contains(x) => "average" 
    case x if ('G' to 'I').contains(x) => "cool" 
    case _ => "unknown" 
} 
+0

是的我認爲這是正確答案,謝謝 –

4

圖案使用逆天可以幫助你做到這

val x = Random.nextInt(30) 

val result = x match { 
case x if x > 0 && x <= 10 => "bad" 
case x if x > 11 && x <= 20 => "average" 
case x if x > 20 && x <= 30 => "cool" 
case _ => "no idea" 
} 

對於字符串,你可以做到這一點

val str = "foo" 

val result = str match { 
case "foo" => "found foo" 
case "bar" => "found bar" 
case _ => "found some thing" 
} 

您可以使用|匹配以及

val result = str match { 
    case "foo" | "bar" => "match" 
    case _ => "no match" 
} 

斯卡拉REPL

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

val x = Random.nextInt(30) 

val result = x match { 
case x if x > 0 && x <= 10 => "bad" 
case x if x > 11 && x <= 20 => "average" 
case x if x > 20 && x <= 30 => "cool" 
case _ => "no idea" 
} 

// Exiting paste mode, now interpreting. 

x: Int = 13 
result: String = average 
+0

我可以這樣做嗎? 「foo」&&「bar」=> –

+1

@DedenBangkit一個字符串不能同時爲'foo'和'bar' – pamu