Created
October 7, 2019 09:06
-
-
Save xuwei-k/4c7c8e768d4c096b27fadc137d5777d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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