你会考虑下面的代码块匹配滥用吗?如果是这样的话,在没有大的if-else-if块的情况下,有什么更优雅的方法呢?
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
}
}发布于 2012-09-24 05:09:57
是的,这是对比赛的滥用。你基本上已经写了一个很大的if-else-if代码块,但是形式更别扭。if语句有什么问题?
我认为直接写这个要干净得多:
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)
}如果你想坚持使用match,你可以将更多的检查转移到匹配本身,这样它就会真正做一些事情:
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)
}
}发布于 2012-09-24 05:10:30
不是的。为什么要滥用?它的可读性相当好。
我看到的问题是money match ...是相当随意的(您只在第一种情况下使用直接模式);一个完整的“滥用”将开始如下所示
() match {
case _ if (money == 0) => 1
...因此,可以坚持使用if-else;您可以组合第二个和第三个条件(if( money < 0 || coins.isEmpty ) ...)
还要注意,尽管您最终“知道”coins不是空的,因此可以“安全地”对其调用head和tail,但这是意外运行时错误的典型来源。coins match { case Nil => ...; case head :: tail => ...}的优点是你不会犯这样的错误。
https://stackoverflow.com/questions/12556236
复制相似问题