Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abuse of match?

Would you consider the following block of code match abuse and if so what's a more elegant way to do it without a big if-else-if block?

def sum(base: Int, xs: List[Int]): Int = {
  base match {
    case 0 => 1
    case _ if (base < 0) => 0
    case _ if (xs.isEmpty) => 0
    case _ => xs.sum
  }
}
like image 541
Chris Avatar asked Sep 23 '12 21:09

Chris


1 Answers

Yes, this an abuse of match. You've basically just written a big if-else-if block, but in a more awkward form. What's wrong with if-statements?

I think it's much cleaner to just write this:

def countChange(money: Int, coins: List[Int]): Int = {
  if(money == 0) 1
  else if (money < 0) 0
  else if (coins.isEmpty) 0
  else countChange(money, coins.tail) + countChange(money - coins.head, coins)
}

If you want to stick with a match, you can move more of the checking into the match itself, so that it's actually doing something:

def countChange(money: Int, coins: List[Int]): Int = {
  (money, coins) match {
    case (0, _) => 1
    case _ if (money < 0) => 0
    case (_, Nil) => 0
    case (_, coinsHead :: coinsTail) => countChange(money, coinsTail) + countChange(money - coinsHead, coins)
  }
}
like image 111
dhg Avatar answered Sep 22 '22 20:09

dhg