In scala, can we use loops inside a recursive function? -


i'm having troubles defining recursive function in scala uses loop. function should go through range of coin denominations (the wallet) , if condition met, returns list of lists; if not, calls again. here code wrote:

def subtractcoin(money: int, wallet: list[int], coins: list[int], coinsset: list[list[int]]): list[list[int]] = {    (i <- 0 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)   } } 

i got following compiling error:

 error: type mismatch;  found   : unit  required: list[list[int]]         (i <- 0 wallet.length) {                ^ 

why imposing result type on loop? there way use loop? foreach alternative? thank in advance.

think happens after recursive call subtractcoin() returns. for comprehension (the proper terminology) has no yield clause statement evaluates unit, isn't subtractcoin() supposed return. error.

instead of advancing index of wallet, better work wallet.head , recurse wallet.tail. (indexing list not efficient.)

also, first rule of recursion? ---> test terminus condition!


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -