cats-effect icon indicating copy to clipboard operation
cats-effect copied to clipboard

Wrapping recursice call in IO

Open brindleoak opened this issue 3 years ago • 1 comments

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.

brindleoak avatar Jul 22 '22 08:07 brindleoak

An example of how it works without IO?

daniel-ciocirlan avatar Jul 22 '22 14:07 daniel-ciocirlan

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

fancellu avatar Jan 02 '23 15:01 fancellu

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

daniel-ciocirlan avatar Jan 03 '23 18:01 daniel-ciocirlan