Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active November 20, 2019 12:54
Show Gist options
  • Save loicdescotte/2052f869bbb116c49d96f2d893b3621e to your computer and use it in GitHub Desktop.
Save loicdescotte/2052f869bbb116c49d96f2d893b3621e to your computer and use it in GitHub Desktop.
Referential Transparency example with Try and IO
import scala.util._
import cats.effect._
//See https://impurepics.com/posts/2018-04-01-referential-transparency.html for RT definition
println("-----------Try--------------")
println("-----------This will print only 1 line : --------------")
val t = Try(println(1+1))
for {
a <- t
b <- t
} yield (a, b)
println("-----------This will print 2 lines : --------------")
for {
a <- Try(println(1+1))
b <- Try(println(1+1))
} yield (a, b)
println("----------IO--------------")
val io = IO.delay(println(1+1))
val program = for {
a <- io
b <- io
} yield (a, b)
val program2 = for {
a <- IO.delay(println(1+1))
b <- IO.delay(println(1+1))
} yield (a, b)
println("-----------This will print 2 lines : --------------")
program.unsafeRunSync
println("-----------This will print 2 lines : --------------")
program2.unsafeRunSync
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment