grokkingfp-examples
grokkingfp-examples copied to clipboard
Simplify a recursion function?
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?
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.