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

Add Defer.recursiveFn to aid in recursion #4656

Merged
merged 2 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
23 changes: 23 additions & 0 deletions core/src/main/scala/cats/Defer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,29 @@ trait Defer[F[_]] extends Serializable {
lazy val res: F[A] = fn(defer(res))
res
}

/**
* Useful when you want a recursive function that returns F where
* F[_]: Defer. Examples include IO, Eval, or transformers such
* as EitherT or OptionT.
*
* example:
*
* val sumTo: Int => Eval[Int] =
* Defer[Eval].recursiveFn[Int, Int] { recur =>
*
* { i =>
* if (i > 0) recur(i - 1).map(_ + i)
* else Eval.now(0)
* }
* }
*/
def recursiveFn[A, B](fn: (A => F[B]) => (A => F[B])): A => F[B] =
new Function1[A, F[B]] { self =>
val loopFn: A => F[B] = fn(self)

def apply(a: A): F[B] = defer(loopFn(a))
}
}

object Defer {
Expand Down
13 changes: 13 additions & 0 deletions tests/shared/src/test/scala/cats/tests/EvalSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -297,4 +297,17 @@ class EvalSuite extends CatsSuite {
assert(n2 == 1)
}
}

test("test Defer.recursiveFn example") {
val sumTo: Int => Eval[Int] =
cats.Defer[Eval].recursiveFn[Int, Int] { recur =>

{ i =>
if (i > 0) recur(i - 1).map(_ + i)
else Eval.now(0)
}
}

assert(sumTo(300000).value == (0 to 300000).sum)
}
}