2016-09-11 73 views

回答

6

是的,這就是所謂的保護:

def myfunct (n: Int, steps: Int) = n match { 
    case 1 => steps 
    case even if n % 2 == 0 => // stuff 
    case odd => // other stuff 
3

使用彭定康匹配衛士

def myfunct (n: Int, steps: Int) = n match { 
case 1 => steps 
case x if x % 2 == 0 => doSomething 
case x => doSomething 
} 

其他方法是定義EvenOdd提取

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 
} 
+0

偶/奇AREN」在這裏真的沒有任何事情可做--Odd和n的奇怪之處沒有任何關係。 @ VictorMoroz的提取器是正確的做法。 –

6

您還可以使用提取:在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") 
} 
2

模式匹配和mod,tupled,

def f(n: Int, steps: Int) = (n, n % 2) match { 
    case (1, _) => steps 
    case (_, 0) => steps + 2 
    case _  => steps + 1 
}