Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active June 24, 2023 08:46
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 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/ee0fd93bb2392fbc664dba85ad6474956e91219a
// 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.3.0"
//> using dep "org.typelevel::cats-effect:3.5.0"
// ---------------------
/*
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(200, 700)
_ <- IO.sleep(delay.millis)
_ <- IO.println(s"$word, $name")
} yield ()
def run = for {
rand <- Random.scalaUtilRandom[IO]
_ <- IO.println("What is your name ?")
name <- IO.readLine
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