Cats effect 3.x Repl that keeps a running sum
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.effect.{IO, IOApp} | |
// Emits intro text, then prompts for integers, keeping a running sum. Will exit upon 'exit' | |
object Repl2 extends IOApp.Simple { | |
def parseInput(input: String): Int = | |
scala.util.Try(input.toInt).toOption.getOrElse(0) | |
def repl(total: Int): IO[Int] = { | |
for { | |
input <- IO.println(s">>> total so far $total >>>") *> IO.readLine | |
number <- if (input == "exit") IO.pure(total) else repl(total + parseInput(input)) | |
} yield number | |
} | |
override def run: IO[Unit] = for { | |
total <- IO.print("Hello, please enter integers, and exit loop with 'exit'") *> repl(0) | |
_ <- IO.println(s"total=$total") | |
} yield () | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment