Wrapping recursice call in IO
In the IO Exercises section around 22:20, Daniel states that: this time it is essential we wrap the recursive fibonacci call in an IO to prevent a stack overflow. However, this worked fine in the previous sumIO exercise without such a technique being needed.
Also, the fibonacci solution seems to work just fine without the extra IO wrap... although it is so computationally intensive maybe we never get to a stack overflow anyway.
An example of how it works without IO?
Like this?
import cats.effect.{IO, IOApp}
object Fib extends IOApp.Simple {
def fib(n: Int): IO[BigInt] = {
if (n <= 1) IO.pure(n)
else
for {
a <- fib(n - 1)
b <- fib(n - 2)
} yield a + b
}
def run = fib(10).flatMap(s => IO.println(s.toString))
}
https://scastie.scala-lang.org/8nsSx1bIT4yrfRQ8iPbXIw
Running fib(100000) will crash. The comment in the course holds true - will close the issue, let's chat on Slack if you need any clarification