Created
May 13, 2020 15:17
-
-
Save fancellu/212ba087922b8f884eb50ab208fd08a7 to your computer and use it in GitHub Desktop.
Cats Eval example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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