Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created July 17, 2023 16:15
Show Gist options
  • Save fancellu/db15a51ce46bb0dba310cf7670420b68 to your computer and use it in GitHub Desktop.
Save fancellu/db15a51ce46bb0dba310cf7670420b68 to your computer and use it in GitHub Desktop.
Cats effect 3.x Repl that keeps a running sum
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