【问题标题】:In scala, can we use loops inside a recursive function?在 Scala 中,我们可以在递归函数中使用循环吗?
【发布时间】: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 对应于钱包(刚刚更正了)。此条件在调用函数之前在代码中进行过滤。

标签: scala loops recursion


【解决方案1】:

想一想subtractCoin() 的递归调用返回后会发生什么。您的for 理解(正确的术语)没有yield 子句,因此该语句的计算结果为Unit,这不是subtractCoin() 应该返回的内容。因此错误。

与其推进wallet 的索引,不如使用wallet.head 并递归使用wallet.tail 可能会更好。 (索引List 效率不高。)

另外,递归的第一条规则是什么? ---> 测试终点条件!

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 2020-09-09
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多