在scala中,我们可以在递归函数中使用循环吗?

在scala中,我们可以在递归函数中使用循环吗?,scala,loops,recursion,Scala,Loops,Recursion,在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

在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)
  }
}
def减法硬币(货币:Int,钱包:List[Int],硬币:List[Int],硬币set:List[List[Int]]):List[List[Int]={
对于(i_))else coinsSet
}
其他减去硬币(货币-钱包(i),钱包,硬币:+钱包(i),硬币集)
}
}
我遇到以下编译错误:

 error: type mismatch;
 found   : Unit
 required: List[List[Int]]
        for (i <- 0 to wallet.length) {
               ^
错误:类型不匹配;
发现:单位
必需:列表[列表[Int]]

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

与其推进
wallet
的索引,不如使用
wallet.head
并使用
wallet.tail
递归(索引
列表
效率不高)


另外,递归的第一条规则是什么?-->Test for the terminus condition!

如果rangeOfcons.length==0会发生什么?它会返回一个List[List[Int]吗?嗨,Dave,对不起,我的错了,错误消息中的rangeOfcons对应于wallet(刚刚更正了它)。在调用函数之前,这个条件会在代码中过滤掉。