2017-07-25 79 views
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可以替代嗎?先謝謝你。

+0

如果rangeOfCoins.length == 0會發生什麼?它會返回一個List [List [Int]]嗎? – dave

+0

嗨戴夫,對不起,我的壞,rangeOfCoins在錯誤消息對應於錢包(剛剛糾正它)。在調用函數之前,會在代碼中過濾此條件。 – Sandra

回答

1

想想遞歸調用subtractCoin()返回後會發生什麼。您的for理解(正確的術語)沒有yield子句,因此語句評估爲Unit,這不是subtractCoin()應該返回的內容。因此錯誤。

而不是推進wallet指數,它可能會更好地使用wallet.headwallet.tail遞歸。 (索引List效率不高。)

此外,遞歸的第一條規則是什麼? --->測試終點條件!

相關問題