Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix foldMap stack safety #702

Merged
merged 3 commits into from
Dec 1, 2015
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions free/src/main/scala/cats/free/Free.scala
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,17 @@ sealed abstract class Free[S[_], A] extends Product with Serializable {
* Run to completion, mapping the suspension with the given transformation at each step and
* accumulating into the monad `M`.
*/
final def foldMap[M[_]](f: S ~> M)(implicit M: Monad[M]): M[A] =
@tailrec
final def foldMap[M[_]](f: S ~> M)(implicit M: Monad[M]): M[A] = {
step match {
case Pure(a) => M.pure(a)
case Suspend(s) => f(s)
case Gosub(c, g) => M.flatMap(c.foldMap(f))(cc => g(cc).foldMap(f))
case Gosub(c, g) => c match {
case Suspend(s) => g(f(s)).foldMap(f)
case _ => throw new Error("Unexpected operation. The case should have been eliminated by `step`.")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to check where else is step used, could it be moved to this function to avoid the exception throwing or does it add value on its own?

}
}
}

/**
* Compile your Free into another language by changing the suspension functor
Expand Down
22 changes: 22 additions & 0 deletions free/src/test/scala/cats/free/FreeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,26 @@ class FreeTests extends CatsSuite {
x.mapSuspension(NaturalTransformation.id[List]) should === (x)
}
}

test("foldMap is stack safe") {
trait FTestApi[A]
case class TB(i: Int) extends FTestApi[Int]

type FTest[A] = Free[FTestApi, A]

def tb(i: Int): FTest[Int] = Free.liftF(TB(i))

def a(i: Int): FTest[Int] = for {
j <- tb(i)
z <- if (j<10000) a(j) else Free.pure[FTestApi, Int](j)
} yield z

def runner: FTestApi ~> Id = new (FTestApi ~> Id) {
def apply[A](fa: FTestApi[A]): Id[A] = fa match {
case TB(i) => i+1
}
}

assert(10000 == a(0).foldMap(runner))
}
}