Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active September 28, 2024 08:58
Show Gist options
  • Save dacr/6c69e74ecce549c9eb14f86689442c10 to your computer and use it in GitHub Desktop.
Save dacr/6c69e74ecce549c9eb14f86689442c10 to your computer and use it in GitHub Desktop.
cats effect example as shown on dedicated typelevel site / published by https://github.com/dacr/code-examples-manager #55065ce7-79b4-4682-8f54-737227aef77b/b56440ae75a6e1190c8f54f03332d348e3708e92
// summary : cats effect example as shown on dedicated typelevel site
// keywords : scala, cats, effect learning, pure-functional, examples
// publish : gist
// authors : typelevel, David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 55065ce7-79b4-4682-8f54-737227aef77b
// created-on : 2022-01-07T14:56:55+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.5.1"
//> using dep "org.typelevel::cats-effect:3.5.4"
// ---------------------
/*
EXAMPLE TAKEN FROM CATS Effect home page : https://typelevel.org/cats-effect/
As show in a PNG file : https://typelevel.org/cats-effect/img/hello-printing.png
*/
import cats.*
import cats.effect.*
import cats.effect.std.Random
import cats.effect.unsafe.implicits.global
import scala.concurrent.duration.*
object Hello extends IOApp.Simple {
def sleepPrint(word: String, name: String, rand: Random[IO]) = for {
delay <- rand.betweenInt(100, 1000)
_ <- IO.println(s"$word, $name").delayBy(delay.millis)
} yield ()
def run = for {
rand <- Random.scalaUtilRandom[IO]
_ <- IO.println("What is your name ?")
name <- IO.readLine.timeout(5.seconds).orElse(IO("joe"))
english <- sleepPrint("Hello", name, rand).foreverM.start
french <- sleepPrint("Bonjour", name, rand).foreverM.start
spanish <- sleepPrint("Hola", name, rand).foreverM.start
_ <- IO.sleep(5.seconds)
_ <- english.cancel &> french.cancel &> spanish.cancel
} yield ()
}
Hello.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment