grokkingfp-examples icon indicating copy to clipboard operation
grokkingfp-examples copied to clipboard

Simplify a recursion function?

Open GodefroyClair opened this issue 1 year ago • 1 comments

Hi, you have written this recursive function in chapter 9 (streams as value):

def lastRates(from: Currency, to: Currency, n: Int): IO[List[BigDecimal]] = {
  if (n < 1) {
    IO.pure(List.empty)
  } else {
    for {
      currencyRate   <- currencyRate(from, to)
      remainingRates <- if (n == 1) IO.pure(List.empty)
                        else lastRates(from, to, n - 1)
    } yield remainingRates.prepended(currencyRate)
  }
}

Is there a reason why you didn't write the (IMH simplest) function :


def lastRates(from: Currency, to: Currency, n: Int): IO[List[Rate]] = {
  if (n <= 1) {
    IO.pure(List.empty)
  } else {
    for {
      currencyRate   <- currencyRate(from, to)
      remainingRates <- lastRates(from, to, n - 1)
    } yield remainingRates.prepended(currencyRate)
  }
}

Maybe I'm missing something?

GodefroyClair avatar Dec 25 '23 11:12 GodefroyClair

Hi @GodefroyClair!

Thanks for reaching out!

The solution in the book includes the currencyRate for n=1 while your solution doesn't.

If you run the program returned from your function when n=1, the program will return an empty List when executed successfully while we expect a List with one element.

Let me know if you have more questions.

miciek avatar Jan 02 '24 14:01 miciek