Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created October 7, 2019 09:06
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 xuwei-k/4c7c8e768d4c096b27fadc137d5777d6 to your computer and use it in GitHub Desktop.
Save xuwei-k/4c7c8e768d4c096b27fadc137d5777d6 to your computer and use it in GitHub Desktop.
package example
case class IO[A](private val run: () => A) {
def unsafeRun(): A = run()
def map[B](f: A => B): IO[B] = IO(() => f(run()))
def flatMap[B](f: A => IO[B]): IO[B] = IO(() => f(run()).run())
}
case class Ref[A](private var value: A) {
def get: IO[A] = IO(() => value)
def set(x: A): IO[Unit] = IO(() => { value = x ; () })
def update(f: A => A): IO[Unit] = {
for {
x <- get
_ <- set(f(x))
} yield ()
}
}
object Ref {
def unsafe[A](a: A): Ref[A] = Ref(a)
def safe[A](a: A): IO[Ref[A]] = IO(() => Ref(a))
}
object Main {
def main(args: Array[String]): Unit = {
val a1 = {
val x = Ref.unsafe(0)
for {
_ <- x.update(_ + 1)
res <- x.get
} yield res
}
val a2 = {
for {
x <- Ref.safe(0)
_ <- x.update(_ + 1)
res <- x.get
} yield res
}
println(a1.unsafeRun)
println(a1.unsafeRun)
println(a1.unsafeRun)
println(a2.unsafeRun)
println(a2.unsafeRun)
println(a2.unsafeRun)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment