Created
May 31, 2017 19:59
-
-
Save anonymous/84d1498244b8e20e01778e9aa77a2390 to your computer and use it in GitHub Desktop.
the description for this gist
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
//Coeval[A] can be seen also as `Function0[A]` | |
val prompt: Coeval[Unit] = Coeval.eval(println("Please enter a number")) | |
val lastPrompt: Coeval[Unit] = Coeval.eval(println(s"Please enter a number, otherwise 42 will be used")) | |
val readLine: Coeval[String] = Coeval.eval(StdIn.readLine()) | |
def promptForNumber(prompt: Coeval[Unit]): Coeval[Int] = | |
for { | |
_ <- prompt | |
s <- readLine | |
} yield s.toInt | |
val num = promptForNumber(prompt) | |
.onErrorRestart(2) | |
.onErrorFallbackTo(promptForNumber(lastPrompt)) | |
.onErrorRecover { | |
case NonFatal(_) => 42 | |
}.memoize // Saves result after first execution | |
println(s"${num.value}") // First call, with side effects and actual computations | |
println(s"${num.value}") // Returns memoized result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment