我需要在scala中使用一堆匹配大小写,我如何使用for或者如果在匹配大小写内,例如:
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
}
谢谢!
答案 0 :(得分:4)
使用Guards进行模式匹配可以帮助您完成此任务
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"
}
Scala 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
答案 1 :(得分:4)
这是一种类似于伪代码的替代方案:
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"
}