0
我在使用循環的scala中定義遞歸函數時遇到了麻煩。該函數應該經過一系列硬幣面值(錢包),並且如果滿足某個條件,它將返回一個列表清單;如果不是,它會再次調用自己。這是我寫的代碼:在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]]嗎? – dave
嗨戴夫,對不起,我的壞,rangeOfCoins在錯誤消息對應於錢包(剛剛糾正它)。在調用函數之前,會在代碼中過濾此條件。 – Sandra