johnsam
johnsam

Reputation: 4572

How to pattern match even number in the case in scala?

I have the following code:

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

Is there anyway to move the even number matching logic into the case ? Do I need a case class?

Such as:

def myfunct(n: Int, steps: Int) = n match {
  case 1 =>  steps
  case (even number??) => ...

Upvotes: 6

Views: 5188

Answers (4)

elm
elm

Reputation: 20415

Pattern match on n and its mod, tupled,

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

Upvotes: 4

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Using Patten Matching guards

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

Other way is to define Even and Odd extractors

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
}

Upvotes: 3

Victor Moroz
Victor Moroz

Reputation: 9225

You can also use extractors:

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")
}

Upvotes: 6

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149578

Yes, it's called a guard:

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

Upvotes: 10

Related Questions