我有以下代碼:如何在scala的情況下模式匹配偶數?
def myfunct(n: Int, steps: Int) = n match {
case 1 => steps
case (x) => if (x % 2 == 0) ...
反正是有移動偶數匹配邏輯成這樣?我需要課堂課嗎?
如:
我有以下代碼:如何在scala的情況下模式匹配偶數?
def myfunct(n: Int, steps: Int) = n match {
case 1 => steps
case (x) => if (x % 2 == 0) ...
反正是有移動偶數匹配邏輯成這樣?我需要課堂課嗎?
如:
是的,這就是所謂的保護:
def myfunct (n: Int, steps: Int) = n match {
case 1 => steps
case even if n % 2 == 0 => // stuff
case odd => // other stuff
使用彭定康匹配衛士
def myfunct (n: Int, steps: Int) = n match {
case 1 => steps
case x if x % 2 == 0 => doSomething
case x => doSomething
}
其他方法是定義Even
和Odd
提取
object One {
def unapply(n: Int) = if (n == 1) Some(1) else None
}
object Even {
def unapply(n: Int) = if (n % 2 == 0) Some(n) else None
}
def myfunct (n: Int, steps: Int) = n match {
case One(x) => steps
case Even(x) => doSomething
case x => doSomething
}
您還可以使用提取:在n
object Even {
def unapply(x: Int) = if (x % 2 == 0) Some(x) else None
}
object Odd {
def unapply(x: Int) = if (x % 2 == 1) Some(x) else None
}
List(1,2,3,4).foreach {
case Even(x) => println(s"$x: even")
case Odd(x) => println(s"$x: odd")
}
模式匹配和mod
,tupled,
def f(n: Int, steps: Int) = (n, n % 2) match {
case (1, _) => steps
case (_, 0) => steps + 2
case _ => steps + 1
}
偶/奇AREN」在這裏真的沒有任何事情可做--Odd和n的奇怪之處沒有任何關係。 @ VictorMoroz的提取器是正確的做法。 –