miciek / grokkingfp-examples

All examples and exercises from the Grokking Functional Programming book
https://www.manning.com/books/grokking-functional-programming?utm_source=michal&utm_medium=affiliate&utm_campaign=book_khan_grokking_6_26_19&a_aid=michal&a_bid=7c041142
126 stars 49 forks source link

Simplify a recursion function? #187

Open GodefroyClair opened 7 months ago

GodefroyClair commented 7 months ago

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?

miciek commented 6 months ago

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.