如何在scala的情况下模式匹配偶数?

时间:2016-09-11 13:39:14

标签: 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 number??) => ...

4 个答案:

答案 0 :(得分:9)

是的,它被称为警卫:

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
}

答案 1 :(得分:6)

您也可以使用提取器:

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 :(得分:3)

使用Patten Matching guards

// On Quantity Change:
var qtys = document.getElementsByName("qty[]");
var i;
for (i = 0; i < qtys.length; ++i) {
    qtys[i].addEventListener("change", totalIt, false);
    qtys[i].addEventListener("input", totalIt, false);
}

其他方式是定义def myfunct (n: Int, steps: Int) = n match { case 1 => steps case x if x % 2 == 0 => doSomething case x => doSomething } Even提取器

Odd

答案 3 :(得分:2)

n及其mod上的模式匹配,tupled,

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