Skip to content

Instantly share code, notes, and snippets.

@fancellu fancellu/Ev.scala
Created May 13, 2020

Embed
What would you like to do?
Cats Eval example
import cats.Eval
object Ev extends App{
// eager, method call
val always: Eval[Int] =Eval.always{
println("running always")
123
}
// lazy, memoized
// at most once
val later: Eval[Int] =Eval.later{
println("running later")
124
}
// super eager, value. Note this outputs even before "About to run"
// exactly once
val now: Eval[Int] =Eval.now{
println("running now")
125
}
println("About to run")
println(always.value)
println(always.value)
println(later.value)
println(later.value)
println(now.value)
println(now.value)
println("about to memoize")
val memo: Eval[Int] =always.memoize
println("memoized")
println(memo.value)
println(memo.value)
object MutualRecursion {
def even(n: Int): Eval[Boolean] = {
println(s"even $n")
Eval.always(n == 0).flatMap {
case true => Eval.True
case false => odd(n - 1)
}
}
def odd(n: Int): Eval[Boolean] = {
println(s"odd $n")
Eval.always(n == 0).flatMap {
case true => Eval.False
case false => even(n - 1)
}
}
}
// stack safe, n could be massive, would still not blow stack
println(MutualRecursion.even(4).value)
}
running now
About to run
running always
123
running always
123
running later
124
124
125
125
about to memoize
memoized
running always
123
123
even 4
odd 3
even 2
odd 1
even 0
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.