本文介绍了滥用比赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您会考虑下面的代码块匹配滥用,如果是这样,没有大的if-else-if块,更优雅的方式是什么?
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
}
}
推荐答案
是的,这是滥用比赛。你基本上只是写了一个大if-else-if块,但是更尴尬的形式。
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)
}
}
这篇关于滥用比赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!