Skip to content

Instantly share code, notes, and snippets.

Created May 31, 2017 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/84d1498244b8e20e01778e9aa77a2390 to your computer and use it in GitHub Desktop.
Save anonymous/84d1498244b8e20e01778e9aa77a2390 to your computer and use it in GitHub Desktop.
the description for this gist
//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