【发布时间】:2017-12-31 19:02:54
【问题描述】:
我在使用循环的 scala 中定义递归函数时遇到了麻烦。该函数应该通过一系列硬币面额(钱包),如果满足某个条件,它会返回一个列表列表;如果没有,它会再次调用自己。这是我写的代码:
def subtractCoin(money: Int, wallet: List[Int], coins: List[Int], coinsSet: List[List[Int]]): List[List[Int]] = {
for (i <- 0 to wallet.length) {
if (money - wallet(i) < 0) {
if (money - coins.reduce(_ + _) == 0) (coinsSet :+ coins.sortWith(_ > _)) else coinsSet
}
else subtractCoin(money - wallet(i), wallet, coins :+ wallet(i), coinsSet)
}
}
我得到以下编译错误:
error: type mismatch;
found : Unit
required: List[List[Int]]
for (i <- 0 to wallet.length) {
^
为什么将结果类型强加于循环?有没有办法使用循环? foreach 会是替代方案吗?先感谢您。
【问题讨论】:
-
如果 rangeOfCoins.length == 0 会发生什么?它会返回一个 List[List[Int]] 吗?
-
嗨,戴夫,对不起,我的错,错误消息中的 rangeOfCoins 对应于钱包(刚刚更正了)。此条件在调用函数之前在代码中进行过滤。